How do I program my adapter in order to visualize the contents of an ArrayList in a onPostExecute inside an AsynkTask?
I have got the following class:
class PlatoCuenta{
public String id;
public String name;
public Integer served_as;
public String served;
public String price;
public String quantity;
public String title_cuenta;
}
I have got the following array list:
ArrayList<PlatoCuenta> bebidas=new ArrayList<PlatoCuenta>();
bebidas=new ArrayList<PlatoCuenta>();
JSONArray mArray = new JSONArray(jsonstr);
for(int i = 0; i < mArray.length(); ++i) {
JSONObject currentObject = mArray.getJSONObject(i);
PlatoCuenta producto= new PlatoCuenta();
SectionItem SectionCuenta = new SectionItem();
producto.id=currentObject.getString("id");
producto.served=currentObject.getString("served");
if(currentObject.getString("price").equals("None"))
producto.price="0.00";
else
producto.price=currentObject.getString("price");
producto.name= currentObject.getString("product_name");
producto.quantity=currentObject.getString("product_number");
producto.served_as = currentObject.getInt("serv_order");
if(producto.served_as==0){
SectionCuenta.title="bebidas";
producto.title_cuenta=SectionCuenta.title;
bebidas.add(producto);
}
if(producto.served_as==2){
SectionCuenta.title="entrantes";
producto.title_cuenta=SectionCuenta.title;
bebidas.add(producto);
}
}
Assume that you have ArrayList<PlatoCuenta> bebidas=new ArrayList<PlatoCuenta>();. The general steps for visualize a listview are:
Create a row layout row.xml
Create an adapter for the row
Set adapter to the listview.
Again, suppose that you already have the design of your row.xml. To create an adapter (step 2).
public class MyAdapter extends BaseAdapter {
public MySimpleArrayAdapter(Context context, ArrayList list) {
super(context, R.layout.rowlayout, values);
//....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row.xml, parent, false);
//continue creating your row here
return rowView;
}
}
And in onPostExecute:
MyAdapter adapter = new MyAdapter(context,bebidas);
listView.setAdapter(adapter);
Good tutorial: Custom ListView
Related
I'm doing an app that uses BaseAdapter to see installed app in an Android device.
In this Listview there are more items, but in the adapter there are only two, and from the second (the package name) I get the other ones
I'm searching a way to sort the items of this adapter for an item that is in the listview, but not in the adapter. Here there is my code:
class AppsAdapter extends BaseAdapter{
private Context mContext;
private List<Pair<String, List<String>>> mAppsWithPermission;
AppsAdapter(Context context, List<Pair<String, List<String>>> appsWithPermission) {
mContext = context;
mAppsWithPermission = appsWithPermission;
}
static class ViewHolder {
TextView appName;
TextView appPermissions;
ImageView appIcon;
TextView Lines;
}
#Override
public int getCount() {
return mAppsWithPermission.size();
}
#Override
public Object getItem(int position) {
return mAppsWithPermission.get(position);
}
#Override
public long getItemId(int position) {
return mAppsWithPermission.get(position).hashCode();
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.appName = convertView.findViewById(R.id.list_item_appname);
holder.appPermissions = convertView.findViewById(R.id.list_item_apppermissions);
holder.appIcon = convertView.findViewById(R.id.list_item_appicon);
holder.Lines = convertView.findViewById(R.id.list_item_lines);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Pair<String, List<String>> item = mAppsWithPermission.get(position);
final PackageManager packageManager = mContext.getPackageManager();
String mAppPer = item.second.toString();
int lineCount = holder.appPermissions.getLineCount();
Log.v("LINE_NUMBERS", lineCount+"");
String strI = Integer.toString(lineCount);
holder.Lines.setText(strI);
if (mAppPer.matches("")) {
holder.Lines.setText("0");
}
});
return convertView;
}
}
When you see "item.second" it's the package name.
As you can think, I'm trying to sort the entire adapter for the descendant value of holder.lines (so StrI).
This is a different question from the others that talks about sorting an adapter, because I want to sort the adapter for an external value.
If you need further informations, you've just to ask me.
I am creating a playlist with 2 lines of name and genre, how to I can delete it.
This is MainActivity :
String[] gene, sl;
...
adp = new Adapter(MainActivity.this, gene, sl);
lv.setAdapter(adp);
This is Adapter
public class Adapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] gene;
private final String[] sl;
SharedPreferences preferences;
public Adapter(Activity context, String[] gene ,String[] sl) {
super(context, R.layout.activity_m , gene);
this.context = context;
this.gene = gene;
this.sl = sl;
}
private class ViewHolder{
TextView txtgene, txtsl;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.activity_m, null, true);
holder = new ViewHolder();
holder.txtgene = (TextView) view.findViewById(R.id.txtgene);
holder.txtsl = (TextView) view.findViewById(R.id.txtsl);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
if (gene[position] != null) {
holder.txtgene.setText(gene[position]);
}
holder.txtsl.setText(sl[position]);
return view;
}
}
How to remove an item when you know its exact position ?
Thank !
You are using the ArrayAdapter constructor that takes an array. This in turn will create an immutable List internal to the ArrayAdapter. So, you will not be able to modify your adapter going this route.
Instead, make a new ArrayList from your array and call the ArrayAdapter constructor that takes a List.
So, change the super call in your Adapter constructor to this:
super(context, R.layout.activity_m, new ArrayList<>(Arrays.asList(gene)));
And then, when you want to remove an item given it's position, do this:
adp.remove(getItem(position));
PS: You should consider refactoring your gene and sl arrays into a class and then use it as the type of your List.
I am trying to create my first Custom Adapter to generate a listview for my android app. I am getting my data from an Api call and then process it and store it in an arraylist:-
class Person{
String bioguide;
String image;
String lastname;
String firstname;
String district;
String state;
String party;}
public static ArrayList<Person> personData = new ArrayList<Person>();
Now in the onpostexecute section I am trying to create a listview and custom adapter to display my data as follows:-
ListView yourListView = (ListView) rootView.findViewById(R.id.state_listView);
ListAdapter customAdapter = new ArrayAdapter<Person>(ByState.this, R.layout.bystate_itemview,personData);
yourListView .setAdapter(customAdapter);
}
}
public class ListAdapter extends ArrayAdapter<Person> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ListAdapter(Context context, int resource, ArrayList<Person> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.bystate_itemview, null);
}
Person p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.last_name);
TextView tt2 = (TextView) v.findViewById(R.id.first_name);
if (tt1 != null) {
tt1.setText(p.getLastname());
}
if (tt2 != null) {
tt2.setText(p.getFirstname());
}
}
return v;
}
}
}
I got the above code following some internet tutorial. The thing is I am getting an error in the line where I use the customadapter first to invoke the constructor of custom adapter. It says cannot resolve constructor. Can someone help me in understanding this. I know I have not defined the proper constructor for my case please let me know the changes. I am creating the listview inside a fragment and the fragment class name is ByState.
In second line replace
ListAdapter customAdapter = new ArrayAdapter<Person>(ByState.this, R.layout.bystate_itemview,personData);
by
ListAdapter customAdapter = new ListAdapter(ByState.this, R.layout.bystate_itemview, personData);
You create your own adapter class, but invoke standart ArrayAdapter
I'm trying to populate a ListView with an ArrayList> using a base adapter. The ArrayList is populated by a database, and it is possible for the database to have no entries, and thus a empty ArrayList, for example when the app is launched for the first time. While the ArrayList is empty, I receive a non de-script "java.lang.RuntimeException: Unable to start activity ComponentInfo ... java.lang.NullPointerException".
My onCreate method looks like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.samples_list_layout);
mContext = getApplicationContext();
lv = getListView();
list = myDatabase.getInstance(mContext).getAllSamples();
sa = new SamplesAdapter(this, list);
lv.setAdapter(sa);
registerForContextMenu(lv);
}
Setting lv.setAdapter(null) will get the app to display the empty list view I have set up. However, when I leave it up to the BaseAdapter, I get the error.
I've followed the 2 Android List8.java and List14.java examples, and either way give the same results.
My BaseAdapter class looks like this:
public class SamplesAdapter extends BaseAdapter {
private static final String SAMPLE_NAME_COL = "name";
private static final String SAMPLE_HOST_COL = "host";
private static final String SAMPLE_ICON_COL = "icon";
private static final String SAMPLE_MODIFIED_STAMP_COL = "moddate";
private Context mContext;
private ArrayList<HashMap<String, String>> samples = new ArrayList<HashMap<String, String>>();
public SamplesAdapter(Context c, ArrayList<HashMap<String, String>> list){
mContext = c;
samples = list;
}
public int getCount() {
return samples.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.samples_row_layout, parent, false);
TextView name = (TextView) v.findViewById(R.id.samples_name);
name.setText(samples.get(position).get(SAMPLE_NAME_COL));
TextView host = (TextView) v.findViewById(R.id.samples_host);
host.setText(samples.get(position).get(SAMPLE_HOST_COL));
TextView moddate = (TextView) v.findViewById(R.id.samples_mod_stamp);
moddate.setText(samples.get(position).get(SAMPLE_MODIFIED_STAMP_COL));
return v;
}
}
I should also note that the ListView properly displays items when there is something to show. It only fails when the ArrayList is empty. Also, I'm using Android 2.2 (Not the greatest, I know). Any help would be greatly appreciated.
let getCount return 0, in orded to avoid the NPE:
public int getCount() {
return (samples == null) ? 0 : samples.size();
}
Is there a working example out there that demonstrates how to append additional rows in ListView dynamically?
For example:
you are pulling RSS feeds from
different domains
you then display the first 10 items
in the ListView (while you have
other threads running in the
background continue pulling feeds)
you scroll and reach the bottom of
the List and click at a button to
view more items
the ListView will then get appended
with additional 10 items, which
makes 20 items now in total.
Any advice how to accomplish this?
Nicholas
To add new item to your list dynamically you have to get adapter class from your ListActivity and simply add new elements. When you add items directly to adapter, notifyDataSetChanged is called automatically for you - and the view updates itself. You can also provide your own adapter (extending ArrayAdapter) and override the constructor taking List parameter. You can use this list just as you use adapter, but in this case you have to call adapter.notifyDataSetChanged() by yourself - to refresh the view.
Please, take a look at the example below:
public class CustomList extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
RowData rd = new RowData("item1", "description1");
data.add(rd);
rd = new RowData("item2", "description2");
data.add(rd);
rd = new RowData("item2", "description3");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row,R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData row = adapter.getItem(position);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(row.mItem);
builder.setMessage(row.mDescription + " -> " + position );
builder.setPositiveButton("ok", null);
builder.show();
}
/**
* Data type used for custom adapter. Single item of the adapter.
*/
private class RowData {
protected String mItem;
protected String mDescription;
RowData(String item, String description){
mItem = item;
mDescription = description;
}
#Override
public String toString() {
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if(null == convertView){
convertView = mInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder {
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder(View row) {
mRow = row;
}
public TextView getDescription() {
if(null == description){
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem() {
if(null == item){
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
You can extend the example above and add "more" button - which just add new items to your adapter (or vector). Regards!