I have an activity that contains several user editable items (an EditText field, RatingBar, etc). I'd like to prompt the user if the back/home button is pressed and changes have been made that have not yet been saved. After reading through the android documentation, it seems like this piece of code should go in the onPause method. I've tried putting an AlertDialog in the onPause however the dialog gets shown and then immediately tears down because nothing is there to block the pause from completing.
This is what I've come up with so far:
@Override
protected void onPause() {
super.onPause();
AlertDialog ad = new AlertDialog.Builder(this).setMessage(
R.string.rating_exit_message).setTitle(
R.string.rating_exit_title).setCancelable(false)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// User selects OK, save changes to db
}
}).setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// User selects Cancel, discard all changes
}
}).show();
}
Am I on the right track or is there another way to accomplish what I'm trying to do here? Any help would be great!