Search code examples
androidlistviewnotifydatasetchangedsectionheader

Is something wrong with my Adapter notifyDataSetChanged()?


I'm trying to use the listview with sectionheaders as mentioned here: Android ListView headers

The values are populated dynamically as shown below:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult called");
    if((requestCode == 1)&&(resultCode == Activity.RESULT_OK)){
        if(data!= null){
            AddedTask=data.getStringExtra("NewTask");
            CategoryName=data.getStringExtra("CategoryItem");
            TaskTime=data.getStringExtra("TaskTime");
            List<Item> items = new ArrayList<Item>();
                items.add(new Header(CategoryName));
                items.add(new ListItem(AddedTask, TaskTime));
                TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(getActivity(), items);
                listViewData.setAdapter(adapter);
                adapter.notifyDataSetChanged();
        }
    }
}

My Problem is when I add the values first time its adding perfect. But when I get the values second time the values are simply updating with the previous values and not showing me the first added values.


Solution


  • When you add some items in the second time, they will replace with the first one, because you declare a new "items" every time.
    You should declare "items" as a public variable outside the onActivityResult function.
    You can do something like this:

    List<Item> items;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult called");
    if((requestCode == 1)&&(resultCode == Activity.RESULT_OK)){
        if(data!= null){
            AddedTask=data.getStringExtra("NewTask");
            CategoryName=data.getStringExtra("CategoryItem");
            TaskTime=data.getStringExtra("TaskTime");
            if (items == null)
                items = new ArrayList<Item>();
            items.add(new Header(CategoryName));
                items.add(new ListItem(AddedTask, TaskTime));
                TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(getActivity(), items);
                listViewData.setAdapter(adapter);
                adapter.notifyDataSetChanged();
        }
    }
    }