Android 1.6: “android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application”

后端 未结 16 1160
滥情空心
滥情空心 2020-11-22 07:46

I\'m trying to open a dialog window, but every time I try to open it it throws this exception:

Uncaught handler: thread main exiting due to uncaught exceptio         


        
相关标签:
16条回答
  • 2020-11-22 08:17

    I had a similar issue where I had another class something like this:

    public class Something {
      MyActivity myActivity;
    
      public Something(MyActivity myActivity) {
        this.myActivity=myActivity;
      }
    
      public void someMethod() {
       .
       .
       AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
       .
       AlertDialog alert = builder.create();
       alert.show();
      }
    }
    

    Worked fine most of the time, but sometimes it crashed with the same error. Then I realise that in MyActivity I had...

    public class MyActivity extends Activity {
      public static Something something;
    
      public void someMethod() {
        if (something==null) {
          something=new Something(this);
        }
      }
    }
    

    Because I was holding the object as static, a second run of the code was still holding the original version of the object, and thus was still referring to the original Activity, which no long existed.

    Silly stupid mistake, especially as I really didn't need to be holding the object as static in the first place...

    0 讨论(0)
  • 2020-11-22 08:18

    Instead of getApplicationContext(), just use ActivityName.this

    0 讨论(0)
  • 2020-11-22 08:18

    As it's said, you need an Activity as context for the dialog, use "YourActivity.this" for a static context or check here for how to use a dynamic one in a safe mode

    0 讨论(0)
  • 2020-11-22 08:22

    The best and the safest way to show a 'ProgressDialog' in an AsyncTask, avoiding memory leak problem is to use a 'Handler' with Looper.main().

        private ProgressDialog tProgressDialog;
    

    then in the 'onCreate'

        tProgressDialog = new ProgressDialog(this);
        tProgressDialog.setMessage(getString(R.string.loading));
        tProgressDialog.setIndeterminate(true);
    

    Now you r done with the setup part. Now call 'showProgress()' and 'hideProgress()' in AsyncTask.

        private void showProgress(){
            new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(Message msg) {
                    tProgressDialog.show();
                }
            }.sendEmptyMessage(1);
        }
    
        private void hideProgress(){
            new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(Message msg) {
                    tProgressDialog.dismiss();
                }
            }.sendEmptyMessage(1);
        }
    
    0 讨论(0)
提交回复
热议问题