Killiam Killiam - 6 months ago 12
Android Question

Instantiating and setting a new custom adapter works, but notifyOnDataSetChanged() does not

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 singleObj = getItem(position); Changed to the statement below
final MyObject singleObj = list.get(position); //this is CORRECT
...
}


I have tried suggestions from the following pages to no avail:



Any help would be appreciated.

Answer

Please try this

private void repopulateListVIew(JSONObject resp) throws JSONException {
    arrayList.clear();
    List<MyObject> newArrayList = getData();
    arrayList.addAll(newArrayList);
    adapter.update(arrayList);
}

and in your CustomAdapter class write following function

public void update(ArrayList<MyObject> list) {
    //replace arrayList variable with you class ArrayList variable
    this.arrayList = list;
    this.notifyDataSetChanged();
}

i hope this will help you