Search code examples
androidlistviewandroid-arrayadapternotifydatasetchanged

Android notifyDataSetChanged not working


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.


Solution

  • create a method in your adapter like:

     public void updateList(){
       notifyDataSetChanged() 
     }
    

    and call this method when you want to refresh the list