Thursday, November 24, 2011

"I can be called only once please" says ...onCreateDialog()

As the title says, I learnt the lesson hard way. I had a code like this:

onCreateDialog(int id, Bundle args) {
switch (id) {
case DELETE_DIALOG: {
final AlertDialog.Builder builder = new Builder(this);
builder.setTitle(R.string.confirm_delete_title)
.setMessage(R.string.confirm_delete_message)
.setPositiveButton(R.string.btn_ok, mFileDialogListener)
.setNegativeButton(R.string.btn_cancel, mFileDialogListener);
//initializeProgressMessageDependingOnId(id);
return builder.create();
// other cases....
}
Now, I was expecting every time a dialog Box is created my initializeProgressMessageDependingOnId() would be called. This would initialize the message that needs to be shown while "DELETE_DIALOG" case is executing in the background. But to my surprise I found that that it does not happen that way. While the first time it invokes the initializeProgressMessage...() method with the "id" (say DELETE_DIALOG) the subsequent calls do not result in invoking the method with different "id". Later I found that once the activiy is created and onCreateDialog is invoked, it stores the information of which dialog box to instantiate for each id. It "does not" invoke the onCreateDialog repeatedly. So once initializeProgressMessageDependingOnId(id) was invoked for the first time, it was never again executed. I rectified it by putting the required method calls inside the "mFileDialogListener" code associated with the dialog box.

private final DialogInterface.OnClickListener mFileDialogListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
handleButtonClick(mCurrentAction);
//handleButtonClick would in turn do the needful
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
}
}
};
};