Friday, March 4, 2011

Android Error: alert dialog crashes during create() or return call

Suppose you launch your main activity named 'myMainActivity' which was mentioned as main activity in your manifest file. Then you navigate to a new page named 'myFiles' page using a new Intent(). Both of these classes extend Activity(). suppose there is a menu option on your 'myFiles' page which allows users to do some operation and based on user's response you have to show some alert dialog. First you will create menu items either using java code or XML file and load them inside. We are not going into that detail. We are going to discuss how to show alert dialog in this case. If you know the place where you need to show the dialog, then write this code there:
showDialog(int_value); //int_value is just a value which is user defined and we will use this to identify our dialog and also android will use this value while calling our dialog handlers.

override onCreateDialog(..) method :
*** If you use the help guides or documents to write this, you will write it as mentioned below and your program will crash while showing the dialog. ****

@Override
protected Dialog onCreateDialog(int id) {
AlertDialog alert = null;
switch( id ) {
case int_value:
AlertDialog.Builder builder = new AlertDialog.Builder(this); //remember it
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}});
alert = builder.create();
}
return alert; //THIS WILL CRASH

}

Reason: Reason is simple. AlertDialog.Builder() constructor expects the current activity's context where this dialog is running. If you give 'this', then it points to context which is for current intent and during show() method, when it tries to associate itself with 'this' pointer's activity, it fails to do so because that is not the main activity.

Solution: Go to your main activity java code. Put a static Context variable say 'myMainContext' and initialize it inside onCreate() method of main activity page. Use that static context variable while constructing your builder class.

So after modification the constructor will be like this: AlertDialog.Builder builder = new AlertDialog.Builder(myMainPage.myMainContext);

This should solve the problem.