Share the post "How To Refresh ListView ArrayAdapter In AsyncTask"
Honestly, I am glad I got this to work the first time. Otherwise, I totally would have been stuck for who knows how long.
It probably had been more than 2 years since I used ListView and modified its contents like adding, removing and updating. When I made another go recently, I was confused why the ListView does not refresh its content.
I thought calling the notifyDataSetChanged() of ArrayAdapter after add() or remove() will do the trick in the onPostExecute() of the AsyncTask class.
The solution is not to use the add() or remove() method of the ArrayAdapter class. Instead, you place a global variable in your class for the ArrayList object that you will pass to the ArrayAdapter.
I instantiate an ArrayAdapter like this:
|
1 |
new MyArrayAdapter(this, R.layout.mylayout, myArrayList); |
Make sure the myArrayList variable is global. So that within your AsyncTask class, you can call add() or remove() method of the ArrayAdapter class within doInBackground() of AsyncTask and call adapter.notifyDataSetChanged() onPostExecute().
That should refresh your ListView contents.
See sample below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
MyAsyncTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { // do something here MyArrayAdapter adapter = (MyArrayAdapter) myListView.getAdapter(); // do something here like delete from database myArrayList.remove(myobj); return null; } @Override protected void onPostExecute(Void result) { ListView myListView = (ListView) findViewById(R.layout.mylistview); MyArrayAdapter adapter = (MyArrayAdapter) myListView.getAdapter(); adapter.notifyDataSetChanged(); } } |