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
protected 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.