15

Hi I am facing a problem in Message dialog, getting Force close my code is here.

in on create:

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.email_result);

    email_result = (Button) findViewById(R.id.email_result_btn);
    email_result.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (diffdays > 365) {

                h.sendEmptyMessage(0);
              }
         }
     }
  }

My Handler:

private Handler h = new Handler() {
    public void handleMessage(Message msg) {
           showMessageDialog("Sorry, you cannot email entries which are earlier than one year ago.");
    }
};

ShowMessageDialog Method:

public void showMessageDialog(String nMessage) {

    alertDialog = new Dialog(Email_Result.this);
    AlertDialog.Builder customBuilder = new AlertDialog.Builder(
            Email_Result.this);
    customBuilder.setMessage(nMessage);
    customBuilder.setPositiveButton(getString(R.string.ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    alertDialog.dismiss();
                }
            });
    alertDialog = customBuilder.create();
    alertDialog.setCancelable(true);
    alertDialog.show();
}

Error Log

01-11 12:08:24.470: ERROR/AndroidRuntime(325): FATAL EXCEPTION: main
01-11 12:08:24.470: ERROR/AndroidRuntime(325): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@44f1dfd8 is not valid; is your activity running?
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.ViewRoot.setView(ViewRoot.java:505)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.app.Dialog.show(Dialog.java:241)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at com.stress1.Email_Result.showMessageDialog(Email_Result.java:207)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at com.stress1.Email_Result$2.onClick(Email_Result.java:81)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.View.performClick(View.java:2408)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.view.View$PerformClick.run(View.java:8816)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.os.Handler.handleCallback(Handler.java:587)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.os.Looper.loop(Looper.java:123)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at java.lang.reflect.Method.invokeNative(Native Method)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at java.lang.reflect.Method.invoke(Method.java:521)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-11 12:08:24.470: ERROR/AndroidRuntime(325):     at dalvik.system.NativeStart.main(Native Method)
Jonik
  • 80,077
  • 70
  • 264
  • 372
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113
  • 1
    please post the **LogCat**, this error usually occurs when you are using `ActivityGroup` – Adil Soomro Jan 10 '12 at 13:24
  • Why you are using handler to show your dialog. you can call showMessageDialog from your onclick also. what is the use of handler in this code? Please check this link why we need handler in our class. http://developer.android.com/reference/android/os/Handler.html – Silvans Solanki Jan 10 '12 at 13:45
  • I had tried without Handler also but got same error see my error also – Jignesh Ansodariya Jan 11 '12 at 06:40

3 Answers3

30

It seems like the Exception occurs when you invoke the show() method on the Dialog. Try using the following code which might circumvent your problem:

 try {
      alertDialog.show();
 } catch(Exception e){
   // WindowManager$BadTokenException will be caught and the app would not display 
   // the 'Force Close' message
 }

Such a problem arises when the activity is trying to display an AlertDialog after it has already been terminated. So, you might want to look closely at how your code works.

Also, your showMessageDialog method could be simplified as follows:

public void showMessageDialog(String nMessage) {

    AlertDialog.Builder customBuilder = new AlertDialog.Builder(Email_Result.this);
    customBuilder.setMessage(nMessage);
    customBuilder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener(){
         @Override            
         public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
         }
    });
    customBuilder.setCancelable(true);
    customBuilder.show();
}
Abhijit
  • 4,853
  • 3
  • 30
  • 33
  • 3
    in response to: "Such a problem arises when the activity is trying to display an AlertDialog after it has already been terminated." ... WindowManager.BadTokenException can also be thrown, as I discovered, on myAlertDialog.show() when it was built using "new AlertDialog.Builder(myActivity.getApplicationContext())". The solution was two steps: 1- make an app-wide static singleton reference to myActivity, 2- use myActivity as the Builder context. – Tom Pace Apr 06 '13 at 16:00
  • 2
    @TomPace - You are treading on unsafe waters there since having a static reference to a context is bound to leak memory. Besides, I fail to see a sound reason behind the solution. – Abhijit Apr 07 '13 at 22:26
  • What is the likelihood of a leak when I use destructor-type code "myStaticRef = null;" ? It's been a while since I dealt with Java memory, assuming that garbage collection worked. But, I'm familiar with memory management techniques from C and Obj-C. Still, I need to be aware. Please inform! – Tom Pace Apr 09 '13 at 13:36
  • 1
    Garbage collection is a little tricky to understand in Java. I am no Java expert, but as far as I know nulling the reference doesn't guarantee that the object will be garbage collected immediately. C and Obj-C offer more control with memory allocation, as you already know. There are several threads on StackOverflow that forbid using static references to a `Context`. You may get by using a static `Context` reference, but you could run into issues at some point, which are hard to track down. Also, you should read this - http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html – Abhijit Apr 09 '13 at 21:28
10

Just add if(!isFinishing) in your code like this :

private Handler h = new Handler() {
    public void handleMessage(Message msg) {
            if(!isFinishing)
           showMessageDialog("Sorry, you cannot email entries which are earlier than one year ago.");
    }
};
Siddharth_Vyas
  • 9,972
  • 10
  • 39
  • 69
  • this was the solution to my question, thank you :) http://stackoverflow.com/questions/24467391/android-progressdialog-show-windowmanager-token-not-valid – Simon. Jun 28 '14 at 14:57
4

Use this following and you will not get Fatal Exception: android.view.WindowManager$BadTokenException exception

if(!Email_Result.this.isFinishing())
{
        customBuilder.show();
}

If you have a context then you can use like following:

if(!((Activity) context).isFinishing())
{
        customBuilder.show();
}
ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24