Update data in Arrayadapter

点点圈 提交于 2019-12-23 06:59:20

问题


i have this problem, i have

private ArrayList<CustomItem> items; 
private ArrayAdapter<CustomItem> arrayAdapter;

i show the data present in items, this data i see in listview, now i want to update data and see this new data

if (!items.isEmpty()) {
    items.clear(); // i clear all data
    arrayAdapter.notifyDataSetChanged(); // first change
    items = getNewData();// insert new data and work well
    arrayAdapter.notifyDataSetChanged();  // second change                                      
}

in the first change i see the data are cleaned, but in second change i don't see the new data in listview, i check and the item don't empty

i don't know where is the error, can you help me? best regads Antonio


回答1:


Assuming the getNewData() function returns ArrayList<CustomItem>, can you change the line:

items=getNewData();

to

items.addAll(getNewData());

and see if that works?




回答2:


This is how I update the Adapter with new data:

            if (arrayAdapter == null) {
                arrayAdapter = new CustomArrayAdapter(getActivity(), data);
                listview.setAdapter(userAutoCompleteAdapter);
            } else {
                arrayAdapter.clear();
                arrayAdapter.addAll(newData);
                arrayAdapter.notifyDataSetChanged();
            }



回答3:


The ArrayList you created in Activity class is an reference variable, which is holding the same reference to the ArrayList in your Adapter class by passing through the constructor (when you initialize the Adapter object).

However, by executing items = getNewData(), you're assigning a new reference to the items in your Activity class, the reference in your Adapter class remains the same, thus you see no changes on the screen.


It's like this:

personA: the ArrayList object in Activity class

personB: the ArrayList object in Adapter class

PersonA and personB they are both holding a map of USA (separately), and the screen shows personB's map. Then someone replaces the map of personA with another coutry's map. Guess what, the screen still shows USA map.


Instead of changing the reference of items, you should use add(), remove(), clear() or addAll() to modify the items's data then call notifyDataSetChanged().



来源:https://stackoverflow.com/questions/11658758/update-data-in-arrayadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!