Search code examples
androidlistviewandroid-adapterbaseadapter

Correct way to refresh a ListView adapter in Android


I have a list of items. I have a button that sends you to another activity in order to create a new item. When the new item is saved an intent sends you back to the activity with the list where the new item should be added. The adapter extends from BaseAdapter without filtering, it just sets the data to the views.

My code is this:

onCreate(){
    ListView listView = findItemById......
    listView.setListeners.......
}

onResume(){
    data = getData();
    adapter = new ListAdapter(context,data);
    listView.setAdapter(adapter);
}

It works but is this correct?

Can I use creation of adapter and setAdapter in onCreate and use notifyDataSetChanged() only in onResume somehow?


Solution

  • I think the correct way to do it is a use

    startActivityForResult(...)
    

    method to launch your Second activity (where your new items is added).

    And in your second activity use

    setResults(RESULT_OK or RESULT_CANCELLED)
    

    (diffrent result when new items is added or user just back to prev screen).

    Then in your ListAdapter class add method

    public void updateData(List data) {
        this.data = new ArrayList<>(data);
        notifyDataSetChanged();
    }
    

    And call it in your onActivityResults(...)

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == YOUR_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            adapter.updateData(...your data from result Intent, or from anywhere else...);
        }
    }
    

    Also i strongly recommend you to use RecyclerView instead of ListView

    UPD: to answer your question - i think that biggest mistake in your code, is to create new instance of ListAdapter object in onResume() method, when it's not necessary