I have an adapter which fills a ListView with 2 TextViews with data from a TreeMap. When the user adds or deletes Data from the ListView, the View should be refreshed.
So here is my Adapter:
public class MyAdapter extends BaseAdapter {
private final ArrayList mData;
public MyAdapter(Map<String, String> map) {
mData = new ArrayList();
mData.addAll(map.entrySet());
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Map.Entry<String, String> getItem(int position) {
return (Map.Entry) mData.get(position);
}
@Override
public long getItemId(int position) {
// TODO implement you own logic with ID
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
} else {
result = convertView;
}
Map.Entry<String, String> item = getItem(position);
// TODO replace findViewById by ViewHolder
((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());
return result;
}}
Because I want to update the view from a dialog and on another question I read, that notifyDataSetChanged()
needs to be called from the UIThread I put my notifyDataSetChanged()
into a Runnable. here is it:
Runnable run = new Runnable(){
public void run(){
Log.v("in the Runnable: ", String.valueOf(colorHashMap));
adapter.notifyDataSetChanged();
}
};
And this it how the Runnable gets called in the Dialog:
DefaultColorActivity.this.runOnUiThread(run);
But I no matter what I try or do, the List just won't get updated. I need to close and reopen the activity to get the new List.
create a method in your adapter
like:
public void updateList(){
notifyDataSetChanged()
}
and call this method when you want to refresh the list
Call notifyDataSetChanged() method from your Adapter class (in getView() method) which extends BaseAdapter after deleting item.
First of all you have to make changes in map (Data source of the adapter). And use Handler class(Android OS Thread) to run the thread like this
Handler handler=new Handler();
handler.post(run);
you can not create object of list.
just create reference and asign list to your list
remove this statement in you adapter class
mData = new ArrayList();
来源:https://stackoverflow.com/questions/28761334/android-notifydatasetchanged-not-working