Ferenc Schenkovski
Ferenc Schenkovski

Reputation: 89

Update ListView even if its adapter is null

I want to update my list even if the adapter is null, but I dont know how to do it.

When I execute the following code my app crashes:

ProductAdapter adapter = new ProductAdapter(context, R.layout.listrow, yal);
if(adapter.getCount()>0){
   lv.setAdapter(adapter);
}else{
   lv.setAdapter(null);
}
adapter.notifyDataSetChanged();
lv.invalidateViews();

Upvotes: 1

Views: 3337

Answers (2)

stefs
stefs

Reputation: 18549

Don't nullify the adapter - the listView always needs one. Instead, nullify the dataset the adapter works with and make sure getCount() returns 0 if the dataset is null (or empty). Or don't nullify the dataset, but make it an empty list or array.

If your data changes, update the adapters dataset and call notifyDatasetChanged() on the adapter. Do not create a new adapter for the ListView when you get new data. This is important for several reasons; e.g. the listViews position won't jump to the top but stay where it is.

Example:

ProductAdapter adapter = new ProductAdapter(context, R.layout.listrow, null);
listView.setAdapter(adapter);

later

adapter.setData(newData);
adapter.notifyDatasetChanged();

Upvotes: 0

Shade
Shade

Reputation: 10001

The adapter is sort of the data source for the list. It provides the individual list items. You can't have a list without an adapter, since then you won't have rows in the list.

Check out the ListView documentation for more information.

Upvotes: 1

Related Questions