Activity has leaked window that was originally added
Asked Answered
D

50

1292

What is this error, and why does it happen?

05-17 18:24:57.069: ERROR/WindowManager(18850): Activity com.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
05-17 18:24:57.069: ERROR/WindowManager(18850): android.view.WindowLeaked: Activity ccom.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.ViewRoot.<init>(ViewRoot.java:231)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.Dialog.show(Dialog.java:239)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.mypkg.myP$PreparePairingLinkageData.onPreExecute(viewP.java:183)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.AsyncTask.execute(AsyncTask.java:391)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.mypkg.myP.onCreate(viewP.java:94)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.os.Looper.loop(Looper.java:123)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-17 18:24:57.069: ERROR/WindowManager(18850):     at dalvik.system.NativeStart.main(Native Method)
Damicke answered 17/5, 2010 at 15:51 Comment(1)
The other classic is when orientation changes: #1112480Emu
R
1716

You're trying to show a Dialog after you've exited an Activity.

[EDIT]

This question is one of the top search on google for android developer, therefore Adding few important points from comments, which might be more helpful for future investigator without going in depth of comment conversation.

Answer 1 :

You're trying to show a Dialog after you've exited an Activity.

Answer 2

This error can be a little misleading in some circumstances (although the answer is still completely accurate) - i.e. in my case an unhandled Exception was thrown in an AsyncTask, which caused the Activity to shutdown, then an open progressdialog caused this Exception.. so the 'real' exception was a little earlier in the log

Answer 3

Call dismiss() on the Dialog instance you created before exiting your Activity, e.g. in onPause() or onDestroy()

Recommit answered 17/5, 2010 at 15:54 Comment(10)
@Override public void onStop() { if (dialog != null) { dialog.dismiss(); dialog = null; }}Vocabulary
Even after 8 years this is still relevant! I got the exception because the activity was closed while it was trying to display my AlertDialog (so Answer 2). In the end I found out that the app was adding a "null" object to the scene (shouldn't have happened but it did) but it didn't give an extra exception for it and the whole thing was masked by the "leaked window" exception instead.Cammack
Is it possible to scan for all open dialogs and close them all in the onStop()? I generate dialogs in a ListView when clicking on items. I am not sure how to retrieve their reference from the onStop.Josephjosepha
Answer 3 is the best solution. worked greatly for me. Thanks kaze, Alex!!Malinger
additional tip if you are displaying the dialog in a loop ensure the loop is exited after activity finishShainashaine
Call dismiss() on the Dialog instance you created before exiting your Activity. solved my problem. So always call dismiss before exiting activityArtema
Very miss leading. After identifying the error causing the activity to close it stopedPolymorphonuclear
This answer is still valid till this date. It worked like charm! Thanks... The error in logcat showed a link that made me go to the line of code that had alertDialog.show();Claude
Answer 2 worked for me. it was misleading. actual error was something elseAuroora
In the case that answer 3 wanting to handle, the StackTrace is not the code that trigger the exception but where the dialog beening shown. It is very misleading.Fourfold
C
424

The solution is to call dismiss() on the Dialog you created in viewP.java:183 before exiting the Activity, e.g. in onPause(). All Windows&Dialogs should be closed before leaving an Activity.

Citrine answered 17/5, 2010 at 18:50 Comment(2)
So when the user rotates the phone, all dialogs should be dismissed?? That doesn't sound right.Moffitt
@Moffitt as you can see, my answer was written more than 7 years ago, and this was definitely true at that time. I no longer work with Android, but based on what I see in the documentation, it might still be the case, but Android has come a long way since (introduced Fragments just to name one), so it is probably easier now.Citrine
P
115

If you are using AsyncTask, probably that log message can be deceptive. If you look up in your log, you might find another error, probably one in your doInBackground() method of your AsyncTask, that is making your current Activity to blow up, and thus once the AsyncTask comes back.. well, you know the rest. Some other users already explained that here :-)

Performance answered 20/7, 2010 at 18:23 Comment(2)
Sometimes in that case I am not able to see the real exception. To find the real exception just comment out the progressDialog.show() and run the app again.. now you see it.Maurita
Hi folks! As mentioned above by @Maurita I am not able to see the real exception as well, What I did? I tracked it using breaking points and I discovered that I was using a reference of an Application class inside the method doInBackground of the AsyncTask class but without declare it in the AndroidManifest file using the property android:name like this: android:name="my.package.MyApplicationClass". A good practice when using AsyncTask it is always remember to instantiate your alert inside the method onPreExecute and dismissing it on onPostExecute.Shampoo
D
80

I triggered this error by mistakenly calling hide() instead of dismiss() on an AlertDialog.

Dandrea answered 7/12, 2011 at 19:29 Comment(2)
Exactly what happened to me. Also, calling hide() and then setting the dialog to null is not a valid alternative either.Nimiety
I would really know the issue behind this. But calling dismiss() helped me!Julissa
E
65

You can get this exception by just a simple/dumb mistake, by (for example) accidentally calling finish() after having displayed an AlertDialog, if you miss a break call statement in a switch statement...

   @Override
   public void onClick(View v) {
    switch (v.getId()) {
        case R.id.new_button:
            openMyAlertDialog();
            break; <-- If you forget this the finish() method below 
                       will be called while the dialog is showing!
        case R.id.exit_button:
            finish();
            break;
        }
    }

The finish() method will close the Activity, but the AlertDialog is still displaying!

So when you're staring intently at the code, looking for bad threading issues or complex coding and such, don't lose sight of the forest for the trees. Sometimes it can be just something as simple and dumb as a missing break statement. :)

Eurydice answered 8/10, 2010 at 8:48 Comment(1)
More or less exactly my issue. Called finish in onError after dialog created, not in onClick for the dismiss button.Terrorstricken
A
65

The answers to this question were all correct, but a little confusing for me to actually understand why. After playing around for around 2 hours the reason to this error (in my case) hit me:

You already know, from reading other answers, that the has X has leaked window DecorView@d9e6131[] error means a dialog was open when your app closed. But why?

It could be, that your app crashed for some other reason while your dialog was open

This lead to your app closing because of some bug in your code, which lead to the dialog remaining open at the same time as your app closed due to the other error.

So, look through your logical. Solve the first error, and then the second error will solve itselfenter image description here

One error causes another, which causes another, like DOMINOS!

Altigraph answered 27/6, 2017 at 0:31 Comment(4)
Can't believe this has only one upvote.. or we are just really bad at programming hahaha I also liked your domino analogyIlluminate
Solve the first error and the second error will not occur. This analogy helped me.Brigade
This is not completely right, instances like phone rotation can also cause "activity" rotation to happen.Furring
Excellent explanation (y)Stupefy
F
39

This problem arises when trying to show a Dialog after you've exited an Activity.

I just solved this problem just by writing down the following code:

@Override
public void onDestroy(){
    super.onDestroy();
    if ( progressDialog!=null && progressDialog.isShowing() ){
        progressDialog.cancel();
    }
}

Basically, from which class you started progressDialog, override onDestroy method and do this way. It solved "Activity has leaked window" problem.

Forsberg answered 30/8, 2012 at 6:55 Comment(1)
onDestroy is not guaranteed to be called. Better to put that code in onPause or onStopDib
F
22

I recently faced the same issue.

The reason behind this issue is that the activity being closed before the dialog is dismissed. There are various reasons for the above to happen. The ones mentioned in the posts above are also correct.

I got into a situation, because in the thread, I was calling a function which was throwing exception. Because of which the window was being dismissed and hence the exception.

Forced answered 8/12, 2011 at 21:12 Comment(0)
F
20

This could help.

if (! isFinishing()) {

    dialog.show();

    }
Folketing answered 26/4, 2013 at 9:47 Comment(1)
Among hundreds of similar answers there is no one showing how to check if windows exists. So you save me some time finding the way to do it. Thanks.Webb
Z
19

Dismiss the dialog when activity destroy

@Override
protected void onDestroy()
{
    super.onDestroy();
    if (pDialog!=null && pDialog.isShowing()){
        pDialog.dismiss();
    }
}
Zennas answered 27/6, 2013 at 11:56 Comment(2)
if pDialog is null this will throw an error as you are querying the state of the null dialogHulett
no it won't @JonDunn, because Java will not process the second boolean if the first one is falseInfundibuliform
P
11

I had the same obscure error message and had no idea why. Given clues from the previous answers, I changed my non-GUI calls to mDialog.finish() to be mDialog.dismiss() and the errors disappeared. This wasn't affecting my widget's behavior but it was disconcerting and could well have been flagging an important memory leak.

Pawnshop answered 27/3, 2011 at 5:49 Comment(1)
Noticed that i was doing a mDialog.hide() before the finish() call. Changing it to mDialog.dismiss() did the trick.Haileyhailfellowwellmet
C
11

I was having the same problem and found this page, and while my situation was different I called finish from a if block before it defined the alert box.

So, simply calling dismiss wouldn't work (as it hasn't been made yet) but after reading Alex Volovoy's answer and realizing it was the alert box causing it. I tried to add a return statement right after the finish inside that if block and that fixed the issue.

I thought once you called finish it stopped everything and finished right there, but it doesn't. It seem to go to the end of the block of code it's in then finishes.

So, if you want to implement a situation where sometimes it'll finish before doing some code you do gotta put a return statement right after the finish or it'll keep on going and and act like the finish was called at the end of the block of code not where you called it. Which is why I was getting all those weird errors.

private picked(File aDirectory){
     if(aDirectory.length()==0){
        setResult(RESULT_CANCELED, new Intent()); 
        finish(); 
        return;
    }
     AlertDialog.Builder alert= new AlertDialog.Builder(this); // Start dialog builder
     alert
        .setTitle("Question")
        .setMessage("Do you want to open that file?"+aDirectory.getName());
    alert
        .setPositiveButton("OK", okButtonListener)
        .setNegativeButton("Cancel", cancelButtonListener);
    alert.show();
}

If you don't put the return right after I called finish in there, it will act as if you have called it after the alert.show(); and hence it would say that the window is leaked by finishing just after you made the dialog appear, even though that's not the case, it still think it is.

I thought I'd add this as here as this shows the finish command acted differently then I thought it did and I'd guess there are other people who think the same as I did before I discovered this.

Counterpunch answered 8/8, 2011 at 0:57 Comment(0)
H
11

I was getting these logs in my video player application. These messages were thrown while the video player was closed. Interestingly, I used to get these logs once in a few runs in a random manner. Also my application does not involve in any progressdialog. Finally, I got around this issue with the below implementation.

@Override
protected void onPause()
{
    Log.v("MediaVideo", "onPause");
    super.onPause();
    this.mVideoView.pause();
    this.mVideoView.setVisibility(View.GONE);
}

@Override
protected void onDestroy()
{
    Log.v("MediaVideo", "onDestroy");
    super.onDestroy();
}

@Override
protected void onResume()
{
    Log.v("MediaVideo", "onResume");
    super.onResume();
    this.mVideoView.resume();
}

Override the OnPause with call to mVideoView.pause() and the set visibility to GONE. This way I could resolve the "Activity has leaked window" log error issue.

Hydrate answered 26/6, 2012 at 13:54 Comment(1)
i also facing same problem. i added your these lines of code in my code but it didn't work and gives the same error "android.view.WindowLeaked that was originally added" and also not play the video and gives "Video cannot be played"Tailrace
B
10

Generally this issue occurs due to progress dialog : you can solve this by using any one of the following method in your activity:

 // 1):
          @Override
                protected void onPause() {
                    super.onPause();
                    if ( yourProgressDialog!=null && yourProgressDialog.isShowing() )
                  {
                        yourProgressDialog.cancel();
                    }
                }

       // 2) :
         @Override
            protected void onDestroy() {
                super.onDestroy();
                if ( yourProgressDialog!=null && yourProgressDialog.isShowing()
               {
                    yourProgressDialog.cancel();
                }
            }
Blackcap answered 15/9, 2017 at 10:7 Comment(0)
T
10

here is a solution when you do want to dismiss AlertDialog but do not want to keep a reference to it inside activity.

solution requires you to have androidx.lifecycle dependency in your project (i believe at the moment of the comment it's a common requirement)

this lets you to delegate dialog's dismiss to external object (observer), and you dont need to care about it anymore, because it's auto-unsubscribed when activity dies. (here is proof: https://github.com/googlecodelabs/android-lifecycles/issues/5).

so, the observer keeps the reference to dialog, and activity keeps reference to observer. when "onPause" happens - observer dismisses the dialog, and when "onDestroy" happens - activity removes observer, so no leak happens (well, at least i dont see error in logcat anymore)

// observer
class DialogDismissLifecycleObserver( private var dialog: AlertDialog? ) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        dialog?.dismiss()
        dialog = null
    }
}
// activity code
private fun showDialog() {
        if( isDestroyed || isFinishing ) return
        val dialog = AlertDialog
            .Builder(this, R.style.DialogTheme)
            // dialog setup skipped
            .create()
        lifecycle.addObserver( DialogDismissLifecycleObserver( dialog ) )
        dialog.show()
}

Tarr answered 29/10, 2019 at 14:9 Comment(0)
T
8

This is not the answer to the question but it's relevant to the topic.

If the activity has defined an attribute in the Manifest

 android:noHistory="true"

then after executing onPause(), the context of activity is lost. So all the view's using this context might give this error.

Tyrolienne answered 9/5, 2016 at 14:25 Comment(2)
Can you relate anything similar for progessdialog.show() .. and progressdialog.hide() in asynctask of the same activity instead of onPause() from activity ?? have a look at my problem... #39333380Hadrian
its working for me perfectly : android:noHistory="true"Pangermanism
T
6

Not only try to show an alert but it can also be invoked when you finish a particular instance of activity and try to start new activity/service or try to stop it.

Example:

OldActivity instance;

    oncreate() {
       instance=this;
    }
    instance.finish();
    instance.startActivity(new Intent(ACTION_MAIN).setClass(instance, NewActivity.class));
Toluca answered 4/3, 2013 at 10:35 Comment(0)
H
6

Try this code:

public class Sample extends Activity(){
@Override
 public void onCreate(Bundle instance){

}
 @Override
    public void onStop() {
        super.onStop();
      progressdialog.dismiss(); // try this
    }

}
Hooked answered 27/3, 2013 at 10:25 Comment(1)
progressdialog.dismiss(); this can create NullPointerException.Overhead
I
5

The "Activity has leaked window that was originally added..." error occurs when you try show an alert after the Activity is effectively finished.

You have two options AFAIK:

  1. Rethink the login of your alert: call dismiss() on the dialog before actually exiting your activity.
  2. Put the dialog in a different thread and run it on that thread (independent of the current activity).
Icelandic answered 13/8, 2012 at 15:29 Comment(0)
L
5

Had the problem where I finished an Activity when a ProgressDialog was still shown.

So first hide the Dialog and then finish the activity.

Logomachy answered 6/3, 2013 at 6:36 Comment(0)
M
5

This can be if you have an error at doInBackground() function and have this code.

Try to add dialog at last. At first check and fix doInBackground() function

protected void onPreExecute() {
     super.onPreExecute();
     pDialog = new ProgressDialog(CreateAccount.this);
     pDialog.setMessage("Creating Product..");
     pDialog.setIndeterminate(false);
     pDialog.setCancelable(true);
     pDialog.show();

 }

 protected String doInBackground(String...args) {
     ERROR CAN BE IS HERE
 }

 protected void onPostExecute(String file_url) {
     // dismiss the dialog once done
     pDialog.dismiss();
Middaugh answered 20/7, 2013 at 7:10 Comment(0)
U
5

This happened to me when i am using ProgressDialog in AsyncTask. Actually i am using hide() method in onPostExecute. Based on the answer of @Alex Volovoy i need to use dismiss() with ProgressDialog to remove it in onPostExecute and its done.

progressDialog.hide(); // Don't use it, it gives error

progressDialog.dismiss(); // Use it
Unpeg answered 19/2, 2016 at 5:29 Comment(1)
This is not really the full answer. There are two ways to leak a dialog. 1) If you have an AsyncTask and you show the Dialog, then something happens which makes the Activity call onPause() (maybe some logic in your AsyncTask itself, like a listener, then it will leak. 2) As mentioned above, theDialog which was created with that Activity Context is never dismissed and the Activity moves on.Hatley
M
5

Might it help to someone who visit this question.

You should check safe condition for activity and dialog before show() and dismiss() dialog.

Add below condition before showing dialog

    if (!isFinishing && !isDestroyed && !dialog.isShowing) {
         dialog.show()
    }

Add below condition before dismiss dialog

    if (!isFinishing && !isDestroyed && dialog.isShowing) {
         dialog.dismiss()
    }
  • isFinishing and isDestroyed will give surety about activity(from where Dialog is initiated) is not in isFinishing or isDestroyed state. Sometimes we try to open Dialog when dialog hosting activity is going to destroy and we facing "leaked window" issue

  • dialog.isShowing to check dialog state before show() or dismiss() dialog.

Mackenie answered 7/11, 2023 at 13:39 Comment(0)
A
4

You have to make Progressdialog object in onPreExecute method of AsyncTask and you should dismiss it on onPostExecute method.

Alvaalvan answered 24/5, 2013 at 11:40 Comment(0)
G
4

Best solution is just add dialog in try catch and dismiss dialog when exception occur

Just use below code

 try {
        dialog.show();
    } catch (Exception e) {
        dialog.dismiss();
    }
Glassware answered 1/11, 2017 at 9:56 Comment(2)
is not dialog will be null after called finished ?, i think dialog.dismiss() will produce error tooStiletto
Exception is already occurred in your case. And you advice call dismiss method in catch block? For what purpose?!Recuperative
F
4

Best solution is put this before showing progressbar or progressDialog

if (getApplicationContext().getWindow().getDecorView().isShown()) {

  //Show Your Progress Dialog

}
Fearless answered 29/6, 2018 at 6:45 Comment(1)
This doesn't work for me. I have Dialog.show() after response from the HTTP call and when in the meantime I rotate the screen Activity is detached but it seems to have isShown == true before Dialog.show() and then Dialog crashes in spite of this checkScion
H
3

In my case, the reason was that I forgot to include a permission in the Android manifest file.

How did I find out? Well, just like @Bobby says in a comment beneath the accepted answer, just scroll further up to your logs and you'll see the first reason or event that really threw the Exception. Apparently, the message "Activity has leaked window that was originally added" is only an Exception that resulted from whatever the first Exception is.

High answered 8/9, 2012 at 17:5 Comment(0)
S
3

Try below code , it will work any time you will dismiss the progress dialogue and it will see whether its instance is available or not.

try {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
Selmaselman answered 14/2, 2014 at 6:16 Comment(0)
P
3

Window leaked exceptions have two reasons:

1) showing the dialog when Activity Context doesn't exists, to solve this you should show the dialog only you are sure Activity exists:

if(getActivity()!= null && !getActivity().isFinishing()){
        Dialog.show();
}

2) not dismiss the dialog appropriately, to solve use this code:

@Override
public void onDestroy(){
    super.onDestroy();
    if ( Dialog!=null && Dialog.isShowing() ){
        Dialog.dismiss();
}
}
Pavilion answered 17/9, 2015 at 20:9 Comment(0)
S
3

Got this error when trying to display a Toast from Background thread. It was solved by running the UI related code on the UI thread

Semiliquid answered 6/8, 2018 at 14:51 Comment(0)
A
2

I have another solution for this, and would like to know if it seems valid to you: instead of dismissing in the onDestroy, which seems to be the leading solution, I'm extending ProgressDialog...

public class MyProgressDialog extends ProgressDialog {

  private boolean isDismissed;

  public MyProgressDialog(Context context) {
    super(context);
  }

  @Override
  public void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    dismiss();
  }

  @Override
  public void dismiss() {
    if (isDismissed) {
      return;
    }
    try {
      super.dismiss();
    } catch (IllegalArgumentException e) {
      // ignore
    }
    isDismissed = true;
  }

This is preferable, AFAIC, because you don't have to hold the progress dialog as a member, just fire(show) and forget

Asante answered 28/3, 2016 at 8:28 Comment(0)
S
2
  if (mActivity != null && !mActivity.isFinishing() && mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }
Skeet answered 27/6, 2016 at 14:17 Comment(0)
M
2

dismiss progressBar before activity destroyed

@Override
    protected void onDestroy() {
        try {
            if (progressDialog != null)
                progressDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
Molnar answered 26/10, 2020 at 9:24 Comment(0)
S
2

Other that hiding your dialog, dismiss it instead.

Replace .hide() with .dismiss()

Subsequent answered 10/1, 2023 at 5:59 Comment(0)
L
1

Just make sure your activity is not closing unexpectedly due to some exceptions raised somewhere in your code. Generally it happens in async task when activity faces force closure in doinBackground method and then asynctask returns to onPostexecute method.

Lempira answered 16/12, 2013 at 9:26 Comment(0)
B
1

I have the same kind of problem. the error was not in the Dialog but in a EditText. I was trying to change the value of the Edittext inside of a Assynctask. the only away i could solve was creating a new runnable.

runOnUiThread(new Runnable(){
      @Override
      public void run() {
       ...        
      }
    });  
Buckman answered 20/5, 2015 at 18:52 Comment(0)
S
1

I also encounter the WindowLeaked problem when run monkey test.The logcat is below.

android.support.v7.app.AppCompatDelegateImplV7$ListMenuDecorView@4334fd40 that was originally added here
android.view.WindowLeaked: Activity com.myapp.MyActivity has leaked window android.support.v7.app.AppCompatDelegateImplV7$ListMenuDecorView@4334fd40 that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:312)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
            at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
            at android.view.Window$LocalWindowManager.addView(Window.java:554)
            at android.support.v7.app.AppCompatDelegateImplV7.openPanel(AppCompatDelegateImplV7.java:1150)
            at android.support.v7.app.AppCompatDelegateImplV7.onKeyUpPanel(AppCompatDelegateImplV7.java:1469)
            at android.support.v7.app.AppCompatDelegateImplV7.onKeyUp(AppCompatDelegateImplV7.java:919)
            at android.support.v7.app.AppCompatDelegateImplV7.dispatchKeyEvent(AppCompatDelegateImplV7.java:913)
            at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:241)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2009)
            at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3929)
            at android.view.ViewRootImpl.deliverKeyEvent(ViewRootImpl.java:3863)
            at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3420)
            at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4528)
            at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4506)
            at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4610)
            at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171)
            at android.os.MessageQueue.nativePollOnce(Native Method)
            at android.os.MessageQueue.next(MessageQueue.java:125)
            at android.os.Looper.loop(Looper.java:124)
            at android.app.ActivityThread.main(ActivityThread.java:4898)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
            at dalvik.system.NativeStart.main(Native Method)

My Activity is AppCompatActivity.And I resovled it with the below code in the Activity.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // added by sunhang : intercept menu key to resove a WindowLeaked error in monkey-test.
    if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}
Schreiner answered 21/6, 2016 at 5:33 Comment(0)
T
1

The issue according to me is you are trying to call a dialog right after an activity is getting finished so according me what you can do is give some delay using Handler and you issue will be solved for eg:

 Handler handler=new Handler();
     handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                     dialog.show();
                     //or
                     dialog.dismiss();

                }
            },100);
Taboret answered 8/12, 2016 at 6:41 Comment(1)
Yes, solution used in #36676912Kopp
M
1

I was using Jetpack Compose and no dialogues so most of these answers were not applicable to me. It turned out that I was accessing out of range array index in a Kotlin coroutine. I wrapped all the coroutine calls in try and catch.

try {
     viewModelScope.launch(Dispatchers.IO) {
     ....
     }
} catch (e: Exception) {
     Log.e("Exception: ", e.message.toString())
}

And finally found the error (or should I say my mistake :P).

Mak answered 4/10, 2021 at 13:29 Comment(0)
K
0

I was using a dialog `onError of a Video Player, and instead of going crazy (I've tested all of these solutions)

I've opted for DialogFragment http://developer.android.com/reference/android/app/DialogFragment.html.

You can return the builder creation in an inner DialogFragment class, just override onCreateDialog

Kirkman answered 18/3, 2014 at 19:21 Comment(0)
A
0

I was also facing this problem for some time but I realized it's not because of dialog in my case it's because of ActionMode. So if you are trying to finish activity when an ActionMode is open it will cause this problem. In your activity's onPause finish the action mode.

 private ActionMode actionMode;

 @Override
 public void onActionModeStarted(ActionMode mode) {
    super.onActionModeStarted(mode);
    actionMode = mode;
 }

 @Override
 protected void onPause() {
    super.onPause();
    if (actionMode != null) actionMode.finish();
 }
Anthelion answered 18/8, 2016 at 4:56 Comment(0)
M
0

Ensure to call this.dialog.show . (Activity)

Mistakable answered 26/11, 2018 at 10:23 Comment(0)
R
0

Maybe you used findViewById in activity instead of dialog.findViewById and set afterwards an OnClickListener on a null instance and that probably caused the original error.

Rondure answered 4/2, 2019 at 11:27 Comment(0)
S
0

If you are dealing with LiveData, when updating value instead of using liveData.value = someValue try to do liveData.postValue(someValue)

Sequester answered 18/4, 2019 at 6:16 Comment(0)
D
0

I am making a scientific app that is already close to 45 thousand lines and I use asynchronous tasks in order to be able to interrupt long tasks, if so desired, with a certain click of the user.

Thus, there is a responsive user interface and sometimes a long task in parallel.

When the long task is over, I need to run a routine that manages the user interface.

So, at the end of an asynchronous task, I do a following action that involves the interface, which cannot be performed directly, otherwise it gives an error. So I use

this.runOnUiThread(Runnable { x(...)})   // Kotlin

Many times, this error occurs in some point of function x.

If function x was called outside a thread

              x(...)  // Kotlin

Android Studio would show a call stack with the error line and one easily could fix the problem in few minutes.

As my source code is tamed, and there is no serious structural problem (many answers above describe this kind of errors), the reason for this scary error message is more gross and less important.

It's just any fool mistake in this execution linked to a thread (like, for example, accessing a vector beyond the defined length), as in this schematic example:

           var i = 10                  // Kotlin
           ...
           var arr = Array(5){""}       
           var element = arr[i]       // 10 > 5, it's a index overflow

Regarding this stupid error, Android Studio unfortunately doesn't point to it.

I even consider it a bug, because Android Studio knows that there is an error, where it is located, but, for some unknown reason, it gets lost and gives a random message, totally disconnected from the problem, i.e, a weird message with no hint showing up.

The solution: Have a lot of patience to run step by step in the debugger until reaching the error line, which Android Studio refused to provide.

This has happened to me several times and I guess it's an extremely common mistake on Android projects. I had never before given this kind of error to me before I used threads.

Nobody is infallible and we are liable to make small mistakes. In this case, you cannot count on the direct help of Android Studio to discover where is your error!

Devisee answered 20/10, 2020 at 21:15 Comment(0)
L
0

如果只是处理DialogActicity.onConfigurationChanged出现的问题

If you just deal with the problem of Dialog in Activity.onConfigurationChanged

//若`AndroidManifest.xml`中已经配置了`android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize"`则不需要设置该项
//If `android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize"` has been configured in `AndroidManifest.xml`, you do not need to set this item
Acticity/Context.registerComponentCallbacks(object : ComponentCallbacks {
    override fun onConfigurationChanged(newConfig: Configuration) {
        dialog?.dismiss()
    }
    override fun onLowMemory() {
    }
})

onDestroy中销毁更保险点

It is safer to destroy in on Destroy

override fun onDestroy() {
    super.onDestroy()
    DialogManager.dismiss()
}

Maybe this is useful for you 👉 https://github.com/javakam/DialogManager

Lomasi answered 8/1, 2021 at 6:29 Comment(1)
f you only deal Dialogin Acticity.onConfigurationChanged(with the problem of If you just deal of problems Dialogin Activity.onConfigurationChanged) Acticity/Context.registerComponentCallbacks(object : ComponentCallbacks { override fun onConfigurationChanged(newConfig: Configuration) { dialog?.dismiss() } override fun onLowMemory() { } }) In onDestroythe destruction of safer points (It IS SAFER to the destroy in on Destroy) override fun onDestroy() { super.onDestroy() DialogManager.dismiss() } My Project github.com/javakam/DialogManagerKelt
K
0

A only answer is

  @Override
    public void onBackPressed() {

        exit_popup();
       // super.onBackPressed(); remove this line

    }
Klos answered 31/5, 2022 at 6:3 Comment(0)
O
0

This is how I solved this bottomSheetDialog.dismiss() the dialog before the finesh() of the activity

  startActivity(Intent(this, Activity::class.java))
        bottomSheetDialog.dismiss()
        finish()
Overhear answered 30/7, 2022 at 12:13 Comment(0)
L
0

Much later than the previous answers, in 2022 where people use Kotlin, we also get the error when Kotlin coroutine tries to modify a popup window from the wrong (non-Main) coroutine context.

Produces error:

CoroutineScope(Dispatchers.IO).launch{
    someCodeThatNeedsOtherContext()
    someViewBinding.someAttribute = someValue // We get the error here
}

Does not produce error:

CoroutineScope(Dispatchers.IO).launch{
    someCodeThatNeedsOtherContext()
    CoroutineScope(Dispatchers.Main).launch{
        someViewBinding.someAttribute = someValue // No error here
    }
}
Laurustinus answered 4/10, 2022 at 6:47 Comment(2)
You should use withContext() to change context instead of CoroutineScope() factory function.Knavish
Ok. Show me how. :)Laurustinus
R
0

There was a database operation inside the dialog method, that caused the Activity to blow up.

Probably at times this log message can be deceptive.

    private fun showDialog() {
        val customDialog = Dialog(requireActivity())
        customDialog.setContentView(R.layout.dialog_custom)
        customDialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        val btnGenerate = customDialog.findViewById(R.id.btnGenerate) as TextView
        val etScheduleNumber = customDialog.findViewById(R.id.etScheduleNo) as AutoCompleteTextView
        val etTripNumber = customDialog.findViewById(R.id.etTripNumber) as AutoCompleteTextView

        viewModel.getBreakdownScheduleNumbers { scheduleNumberList->
            val adapter = CustomAdapter(requireContext(),
                scheduleNumberList as ArrayList<String>)
            etScheduleNumber.setAdapter(adapter)
        }

        btnGenerate.setOnClickListener {

        }
        customDialog.show()
    }
Ravel answered 24/1 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.