I'm experiencing an issue with notifyOnDataSetChanged().
I am able to get my list view to load new data by creating a new CustomAdapter, but not by using notifyOnDataSetChanged().
private void repopulateListView(JSONObject resp) throws JSONException {
arrayList.clear();
List<MyObject> newArrayList = getData();
arrayList.addAll(newArrayList); //I've checked that arrayList contains new data
/* WORKS, new data is loaded in the list view */
adapter = new CustomAdapter(MainActivity.this, arrayList);
listView.setAdapter(adapter);
}
whereas the following doesn't work - the list view is not refreshed, it simply stays as it was before retrieving new data. I have checked that the new data is correctly retrieved.
private void repopulateListVIew(JSONObject resp) throws JSONException {
arrayList.clear();
List<MyObject> newArrayList = getData();
arrayList.addAll(newArrayList); //I've checked that arrayList contains new data
/* DOES NOT WORK, list view does not refresh with new data */
((BaseAdapter)adapter).notifyOnDataSetChanged();
}
My adapter was defined like so:
adapter = new CustomAdapter(MainActivity.this, arrayList);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//additional code
startActivity(DetailsActivity);
}
}
);
UPDATE: @Sabeeh's answer worked. Based on answers from @Sabeeh and @ViniciusRodriguesLima below, I had to edit my CustomAdapter.java as follows to reference the list
variable (in addition to adding the update() method):
public class CustomAdapter extends ArrayAdapter<MyObject> {
private Context context;
private List<MyObject> list = new ArrayList<>(); //add this variable
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inf = LayoutInflater.from(getContext());
View customView = inf.inflate(R.layout.custom_beer_row, parent, false);
//final MyObject chosenObj = getItem(position); Changed to the statement below
final MyObject chosenObj = list.get(position); //this is CORRECT
...
}
I have tried suggestions from the following pages to no avail:
- notifyDataSetChange not working from custom adapter
- notifyDataSetChanged not working
- Android: notifyDataSetChanged(); not working
- Following the instructions on the top-voted answer, using
adapter.clear()
seems to clear myarrayList
as well, so by the time I use notifyOnDataSetChanged(), thearrayList
is empty)
- Following the instructions on the top-voted answer, using
Any help would be appreciated.