mike_x_
mike_x_

Reputation: 1929

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?

Upvotes: 2

Views: 7504

Answers (3)

Shanmugam
Shanmugam

Reputation: 301

Hi OnActivityResult read all data create the new object and add to the list and call notifyDatasetChanged() , i will automatically refresh ui

Upvotes: 0

Hank Moody
Hank Moody

Reputation: 354

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

Upvotes: 2

PEHLAJ
PEHLAJ

Reputation: 10126

Add this method to your adapter and then call it with new data using adapter.udpateData(data):

public void updateData(List data) {

  this.data = data;
  notifyDataSetChanged();
}

Also, you can use notifyItemRangeInserted(0, data.size())

Upvotes: 1

Related Questions