I'm developing an Android 2.2 app.
I use a dialog to ask user for his nickname. This is my source code:
private void showDialog() {
//set up dialog
final Dialog dialog = new Dialog(UserStatsActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.createuserrow);
dialog.setOnDismissListener(this);
//set up button
Button button = (Button) dialog.findViewById(R.id.saveUser);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView nameTextView = (TextView)dialog.findViewById(R.id.userName);
userNickName = nameTextView.getText().toString().trim();
if ((userNickName.length() > 0) &&
(userNickName.length() < 9)){
saveUser = true;
dialog.dismiss();
}
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
public void onDismiss(DialogInterface arg0) {
try {
if (saveUser) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
User.saveUser(getApplicationContext(), userNickName);
Editor editor = prefs.edit();
editor.putString(USER_NAME, userNickName);
editor.putBoolean(FIRST_TIME_RUN, false);
editor.commit();
loadPreferences();
}
}
catch (Exception ex){
Log.e(Constants.APP_TAG, "UActivity: " + ex.getMessage());
showAlert(this.getString(R.string.errorClose));
}
}
If I press home key while dialog is shown. When I start app again, and I click on save button, dialog is shown again.
I've debug my code and it is working perfectly, but the dialog is still open.
What's happening?
Thanks.
I would use the methods onCreateDialog() and onPrepareDialog(). By doing this, you get a lot more control over when dialogs get populated and shown.
onCreateDialog() fires when the dialog is shown for the first time. This method is the one to setup your dialog in.
onPrepareDialog() fires right before it is shown each time. This method is the one to change options in each subsequent time.
This is how the onCreateDialog(int id) method could be used in your case. Now, keep in mind that above, I did not take into account any other dialogs that you could create, so you should assign a constant Int to your Dialog and determine from within this method.
Also keep in mind the fact that this method only gets called the first dialog. You must use:
To repopulate for each subsequent dialog, or add
removeDialog(int DIALOG_ID);
to your onClick.