Search code examples
androidandroid-listviewnotifydatasetchanged

Adding data at the specific position of Listview in android


I have a listview and I have to add two more element in listview. I have to add notifyDataSetChanged() . but not sure how to do it.

listView = (ListView) findViewById(R.id.my_listview);
myListAdapter = new MyListAdapter (this, sourceList);
listView.setAdapter(myListAdapter);
myListAdapter.notifyDataSetChanged();

sourceList is the List .

I need to add 2 items at the end of the Listview. Thanks.


Solution

  • Just add your desired data to the adapter. For example:

    myListAdapter.add(obj1);
    

    The newly added data will be attached at the end of your ListView.

    Remember: when injecting data directly into an Adapter, you don't need to call its notifyDataSetChanged method.

    If you modify your sourceList object, in that case its necessary to call notifyDataSetChanged method in order for the Adapter to refresh its contents.