144

I try to connect to Facebook throught Facebook API, I follow this example: https://github.com/facebook/facebook-android-sdk/tree/master/examples/simple

Everything is ok, but when I try to edit some code, I mean I want to display the dialog post message after the login is successful like this:

public void onAuthSucceed() {
        mText.setText("You have logged in! ");   
        //This is the code to call the post message dialog.                     
        mFacebook.dialog(Example.this, "feed",new SampleDialogListener());   
    }

I receive this error in the logcat:

03-02 13:32:08.629: E/AndroidRuntime(14991): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405180f8 is not valid; is your activity running?
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.ViewRoot.setView(ViewRoot.java:532)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.Window$LocalWindowManager.addView(Window.java:424)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.app.Dialog.show(Dialog.java:241)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook.dialog(Facebook.java:780)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook.dialog(Facebook.java:737)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Example$SampleAuthListener.onAuthSucceed(Example.java:113)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.SessionEvents.onLoginSuccess(SessionEvents.java:78)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Example$LoginDialogListener.onComplete(Example.java:88)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook$1.onComplete(Facebook.java:320)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:144)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:218)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:337)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.os.Looper.loop(Looper.java:130)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.app.ActivityThread.main(ActivityThread.java:3687)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at java.lang.reflect.Method.invokeNative(Native Method)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at java.lang.reflect.Method.invoke(Method.java:507)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at dalvik.system.NativeStart.main(Native Method)

Any idea?

Adinia
  • 3,722
  • 5
  • 40
  • 58
Han Tran
  • 2,073
  • 4
  • 22
  • 37
  • possible duplicate of [Error : BinderProxy@45d459c0 is not valid; is your activity running?](http://stackoverflow.com/questions/7811993/error-binderproxy45d459c0-is-not-valid-is-your-activity-running) – bsara Dec 09 '14 at 21:35
  • 1
    Check the answer below. I've mark it's correct :) – Han Tran Dec 10 '14 at 02:46
  • Just because you've marked the answer doesn't change the fact that this is a duplicate question. The other was asked first and is an identical issue with an essentially identical answer. – bsara Dec 10 '14 at 05:50
  • 1
    Did you see that my question is 2 years ago? – Han Tran Dec 10 '14 at 07:13
  • Yes I did. And the other was asked 3 years ago. Its really not a big deal, that is how the forum works. We try to consolidate duplicated questions. – bsara Dec 10 '14 at 07:25
  • 1
    So look like others Moderator has mistake but you :)) Anw, thanks! – Han Tran Dec 10 '14 at 08:11
  • This can be caused by a bug in Android 7.1. See answer at https://stackoverflow.com/a/52437888/924369 using https://github.com/drakeet/ToastCompat. – Glenn Sep 27 '18 at 03:26

18 Answers18

183

I was seeing this error reported once in a while from some of my apps, and here's what solved it for me:

if(!((Activity) context).isFinishing())
{
    //show dialog
}

All the other answers out there seem to be doing weird things like iterating through the list of running activities, but this is much simpler and seems to do the trick.

DiscDev
  • 38,652
  • 20
  • 117
  • 133
  • 10
    it doesn't solve the problem, it prevents crash and showing dialog as well – YTerle Aug 11 '16 at 14:32
  • 7
    Just remember you should check `context instanceof Activity` or you may get an `Exception` ! – FtheBuilder Oct 16 '16 at 18:40
  • 3
    or you can use getActivity().isFinishing() instead of context – Nikita Axyonov Oct 18 '16 at 09:23
  • I am using API-23 . When i try to use this in my MainActivity which extends AppCompatActivity. It shows me a error like Caused by: java.lang.ClassCastException: com.creativeapp.hindihdvideosongs.AppController cannot be cast to android.app.Activity at com.creativeapp.hindihdvideosongs.MainActivity.onCreate(MainActivity.java:145) AppController is added into my AndroidMenifest – pavel Dec 12 '16 at 07:59
  • I am not using any dialogue and getting this error. – Abdul Waheed Sep 04 '19 at 07:48
  • Well, it's android. There is no solid steady solution on anything. 2+2 can equal 4 and 5 and 6. Sometimes we just have to pray to have fewer crashes. – ekashking Feb 21 '22 at 01:51
142

This can occur when you are showing the dialog for a context that no longer exists. A common case - if the 'show dialog' operation is after an asynchronous operation, and during that operation the original activity (that is to be the parent of your dialog) is destroyed. For a good description, see this blog post and comments:

http://dimitar.me/android-displaying-dialogs-from-background-threads/

From the stack trace above, it appears that the facebook library spins off the auth operation asynchronously, and you have a Handler - Callback mechanism (onComplete called on a listener) that could easily create this scenario.

When I've seen this reported in my app, its pretty rare and matches the experience in the blog post. Something went wrong for the activity/it was destroyed during the work of the the AsyncTask. I don't know how your modification could result in this every time, but perhaps you are referencing an Activity as the context for the dialog that is always destroyed by the time your code executes?

Also, while I'm not sure if this is the best way to tell if your activity is running, see this answer for one method of doing so:

Check whether activity is active

Community
  • 1
  • 1
Peter Pascale
  • 1,538
  • 1
  • 15
  • 10
22

one simple workaround is to catch the exception :

try {
        alertDialog.show()
    }
catch (WindowManager.BadTokenException e) {
        //use a log message
    }

It's not elegant but sometimes easy when you have to manage async operations and you are not sure wether activity is up or not when you want to show the dialog.

gerz
  • 231
  • 2
  • 3
13
  • In my case the issue is occurred because of am trying to open/show dialog box in onPostExecute AsyncTask

  • However its an wrong method of showing dialog or Ui changes in onPostExecute.

  • For that, we need to check the activity is in active Eg : !isFinishing() , if the activity is not finished then only able to show our dialog box or ui change.

    @Override
    protected void onPostExecute(String response_str) {
    
       getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((Activity) mContext).isFinishing()) {
                            try {
                                ShowAgilDialog();
                            } catch (WindowManager.BadTokenException e) {
                                Log.e("WindowManagerBad ", e.toString());
                            }
                        }
                    }
                });
    }
    
Agilanbu
  • 2,747
  • 2
  • 28
  • 33
1

I faced exactly the same issue. Calling '(!isFinishing())' prevented the crash, but it could not display the 'alert' message.

Then I tried making calling function 'static', where alert is displayed. After that, no crash happened and message is also getting displayed.

For ex:

public static void connect_failure() {      
        Log.i(FW_UPD_APP, "Connect failed");

        new AlertDialog.Builder(MyActivity)
        .setTitle("Title")
        .setMessage("Message")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                  //do nothing
            }
         })
        .setIcon(R.drawable.the_image).show();      
    }
BenMorel
  • 34,448
  • 50
  • 182
  • 322
ArunJTS
  • 264
  • 5
  • 15
1

After execute the thread, add these two line of code, and that will solve the issue.

Looper.loop();
Looper.myLooper().quit();
JonathanDavidArndt
  • 2,518
  • 13
  • 37
  • 49
1

Another developer use case: If the WindowManager or getWindow() is being called on onCreate() or onStart() or onResume(), a BadTokenException is thrown. You will need to wait until the view is prepared and attached.

Moving the code to onAttachedToWindow() solves it. It may not be a permanent solution, but as much as I could test, it always worked.

In my case, there was a need to increase the screen brightness when the activity became visible. The line getWindow().getAttributes().screenBrightness in the onResume() resulted in an exception. Moving the code to onAttachedToWindow() worked.

Ram Iyer
  • 1,621
  • 1
  • 23
  • 25
1

Unable to add window -- token is not valid; is your activity running?

This crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed.

External resources

Android – Displaying Dialogs From Background Threads

Error : BinderProxy@45d459c0 is not valid; is your activity running?

Bholendra Singh
  • 980
  • 7
  • 14
1

how's I handled is every time dismissing and doing null the dialog reference before showing dialog

public static void showProgressDialog(Context context){
    if (context==null)return;
    //do force null when trigger this method to avoid Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?
    if (dialog!=null && dialog.isShowing()){
        dialog.dismiss();
        dialog=null;
    }
    dialog=new Dialog(context);

    dialog.setCancelable(false);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setContentView(ProgressBarLayoutBinding.inflate(LayoutInflater.from(context)).getRoot());
    if ((context instanceof AppCompatActivity  &&  !((AppCompatActivity) context).isFinishing()) && !dialog.isShowing()) {
        dialog.show();
    }
}
Mohd Qasim
  • 896
  • 9
  • 20
1

Problem

dialog.show(); // Getting error here...

Solution

private void Dialog(){
    if(!isFinishing()) { //by checking the activity is finished. We can solve this issue....
        dialog = new ProgressDialog(YourActivity.this);
        dialog.setMessage("Loading...");
        dialog.setCancelable(false);
        dialog.show(); 
    }
}
JustSightseeing
  • 1,460
  • 3
  • 17
  • 37
1

Check if the activity is finishing and its not null before showing the dialog.

if(activity != null && !activity.isFinishing()) {

//show dialog here

}

0

Just move your dialog code on Ui thread like this:

runOnUiThread{
// your dialog code or function
}
JustSightseeing
  • 1,460
  • 3
  • 17
  • 37
DrApps
  • 11
  • 1
0

For all who the "!isFinishing()" solution didn't work for them:

try to re-initialize the dialog also in onResume() .

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 14 '23 at 05:00
0

Check what context you are passing to create a dialog box that is also a important, in my case i was calling from common class due to which it was not taking the proper context so i pass the context in function and it work.

For eg: CommonClass.getInstance(context).showDialog(context)

-1

For me it was fixed by just removing the static property in the DialogHelper.class methods (resposble for creating & hiding the dialog), as I have properties related to Window in those methods

Dasser Basyouni
  • 3,142
  • 5
  • 26
  • 50
-1

What you should do is to check if activity is finishing before showing alert. For this purpose isFinishing() method is defined within Activity class.

Here is what you should do:

if(!isFinishing())
 {
     alert.show();
 }
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37
-1
if ((context instanceof AppCompatActivity && !((AppCompatActivity) context).isFinishing()) && !dialog.isShowing()) {
    dialog.show();
}

Try this, the dialog will be only called while the activity is alive else it won't.

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
Rajesh Khan
  • 59
  • 1
  • 4
-2

Under dependencyServices nothing of the above helped me, i ended up doing like below:

    class Static_Toast_Android
    {
        private static Context _context
        {
            get { return Android.App.Application.Context; }
        }
        public static void StaticDisplayToast(string message)
        {
            Toast.MakeText(_context, message, ToastLength.Long).Show();
        }
    }
    public class Toast_Android : IToast
    {

        public void DisplayToast(string message)
        {
            Static_Toast_Android.StaticDisplayToast(message);
        }
    }

I must use the "double-class" because an interface cannot be static. L-

Legion
  • 760
  • 6
  • 23