I have a ListView populated by a SimpleAdapter, which gets values from an ArrayList of HashMaps. The arraylist is built by a method load() that fetches data from a site of mine. I have a menu option that allows to refresh data by fetching them again and calling adapter.notifyDataSetChanged() and it actually works fine, updating the arraylist and refreshing the ListView as well. Now, it takes a few seconds for load() to establish the http connection and get the data so I wanted to set up a ProgressDialog to inform the user of the ongoing process. I know I can’t put the ProgressDialog on the ui thread where load() works, so I tried with an AsyncTask. It works fine, showing the dialog while the new data are being fetched and passed to the adapter, but it also adds a problem: the ListView doesn’t refresh the displayed items anymore, unless I scroll the modified list item out of the screen and back, then it would show the new content. What can I do to have both the ProgressDialog and the refresh of the list contents?
This is the code with the ProgressDialog in the AsyncTask (edits data but doesn’t trigger list refresh on screen):
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.update: {
loading.show(); //the ProgressDialog
AsyncTask<Void, Void, Void> loadingTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
load(); //fetching data, takes a while
return null;
}
@Override
protected void onPostExecute(Void result) {
loading.dismiss();
}
};
loadingTask.execute();
adapter.notifyDataSetChanged();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
This is the code that would refresh the ListView as well as the data behind (but won’t let me set up a ProgressDialog):
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.update: {
load();
adapter.notifyDataSetChanged();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
Just add
onPreExecute()of AsycTask andshow()ProgressDialogfrom it. and putadapter.notifyDataSetChanged();inonPostExecute()of AsyncTask.Like,