Reputation: 447
I have an alertbox I use for showing errors. It is in a general utility class that I can call from any activity. When I call the error box, I pass the current activity along with the error message.
Util.showAlert(this,"error message goes here");
My showAlert looks like this
AlertDialog alertDialog = new AlertDialog.Builder(act).create();
// Setting Dialog Title
alertDialog.setTitle("ERROR");
// Setting Dialog Message
alertDialog.setMessage(msg);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
I ran into a recent problem and not sure the best way to fix this for this issue and any future ones calling the same generic alertbox. My MainActivity calls a SecondActivity. In the onCreate for that activity, I do some processing and then need to open a database and get some info. If the info is not available, I can't run the SecondActivity and therefore must exit and return to the MainActivity.
In my error checking routine in the SecondActivity, I check to see if I have the data... if I do, I continue. If not, I call:
Util.showAlert(this,"Whoops, we have a problem");
finish();
The problem is, the finish() fires and the SecondActivity closes BEFORE the showAlert opens.
Under normal circumstances with an error, I am still in that activity. In this case, I am not.
Whats the best way to handle this?
Upvotes: 1
Views: 1013
Reputation: 132982
The problem is, the finish() fires and the SecondActivity closes BEFORE the showAlert opens.
Finish Activity after showing Alert or when user press OK
button on AlertDialog by calling :
act.finish();
in onClick
method of AlertDialog
.
Upvotes: 1
Reputation: 16127
You need change your logic in code show dialog, flow me AlertDialog alertDialog = new AlertDialog.Builder(act).create();
// Setting Dialog Title
alertDialog.setTitle("ERROR");
// Setting Dialog Message
alertDialog.setMessage(msg);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
act.finish(); // act is Activity(context) showing Alert
}
});
// Showing Alert Message
alertDialog.setCancelable(false) // cannot dismiss without Ok button
alertDialog.show();
}
and in case Error you only call
Util.showAlert(this,"Whoops, we have a problem");
Upvotes: 0