Android Retry/Cancel Dialog
I have the following problem. My main activity consists of a ListView populated with the data obtained from a web service. When the main activity is first loaded, in case the data can't be retrieved from the web, I want to display a dialog with 2 buttons, 'Retry' and 'Cancel'. If the user clicks on 'Reply', the reload data method is called, and if there's any exception, the dialog should appear again.
I haven't found a way yet to implement my desired behavior.
@Override
protecte开发者_Python百科d void onResume() {
super.onResume();
Log.i("ItemListActivity", "onResume()");
if(isNewInstance) {
reloadItems();
isNewInstance = false;
}
}
private void reloadItems() {
try {
itemService.reloadItems();
items = itemService.getItemList();
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
showDialog(RETRY_DIALOG);
}
}
protected Dialog onCreateDialog(int id) {
switch(id) {
case RETRY_DIALOG:
return new AlertDialog.Builder(this).setTitle(R.string.retryDialog_title)
.setPositiveButton(R.string.retryDialog_retry, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
reloadItems();
}
})
.setNegativeButton(R.string.retryDialog_quit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create();
}
return null;
}
The first time the reloadItems() is called from onResume() and an exception is encountered, the dialog is displayed. But when I click the "Retry" button and this time reloadItems() is called from the dialog's onclicklistener, the dialog isn't displayed second time, I guess because the onclicklistener will return only after the the reloadItems() has returned the second time.
I tried to run reloadItems() in a new thread from onClick(), but the code still runs in the main thread. If I run reloadItems() from onResume() in a new thread, the code runs in a new thread.
What I also noticed while debugging is that the dialog isn't showed right after showDialog(RETRY_DIALOG) returns, only after the reloadItems() returns.
As what I want to do is quite common behavior I'm sure that there is a "best practice" solution to this. I'm totally new to Android and I'm not used with this style.
You should be running your reloadItems method in an ASyncTask.
These run your web access and download process in a background thread and allow you to post UI updates ON THE UI THREAD.
You can also handle the exception in the background thread and then post an update to the UI thread that shows your dialog. Don't forget to kill your task after this failure update or it will keep trying to run and think it finished successfully.
Also important, you have to create a NEW INSTANCE of your task each time it runs (so on the onClick listener for the Retry button for example. Reusing a task will cause an exception.
精彩评论