[android] android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

I am working with Android application to show network error.

NetErrorPage.java

package exp.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NetErrorPage extends Activity implements OnClickListener {    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.neterrorlayout);
        Button reload=(Button)findViewById(R.id.btnReload);
        reload.setOnClickListener(this);    
        showInfoMessageDialog("Please check your network connection","Network Alert"); 
    }

    public void onClick(View arg0)             
        {
            if(isNetworkAvailable())
            {                   
                Intent myIntent = new Intent((Activity)NetErrorPage.this, MainActivity.class);   
                myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);              
                ((Activity)NetErrorPage.this).startActivity(myIntent);
                finish();
            }
            else
                showInfoMessageDialog("Please check your network connection","Network Alert");
    }

    public void showInfoMessageDialog(String message,String title)
       {
        AlertDialog alertDialog = new AlertDialog.Builder(NetErrorPage.this).create();
        alertDialog.setTitle("Network Alert");
        alertDialog.setMessage(message);
        alertDialog.setButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) 
                    {   
                        dialog.cancel();
                    }
                });            
        alertDialog.show();
    }

 private boolean isNetworkAvailable()
    {
        NetworkInfo ActiveNetwork;
        @SuppressWarnings("unused")
        String IsNetworkConnected;
        @SuppressWarnings("unused")
        String ConnectionType;
        ConnectivityManager connectivitymanager;
        connectivitymanager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);        
        try
        {           
            ActiveNetwork=connectivitymanager.getActiveNetworkInfo();
            ConnectionType=ActiveNetwork.getTypeName(); 
            IsNetworkConnected=String.valueOf(ActiveNetwork.getState());
            return true;                        
        }
        catch(Exception error)
        {
                return false;
        }
    }    
}

but i'm getting the error as below,

08-17 11:59:08.019: E/WindowManager(16460): Activity exp.app.NetErrorPage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40534a18 that was originally added here
08-17 11:59:08.019: E/WindowManager(16460): android.view.WindowLeaked: Activity exp.app.NetErrorPage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40534a18 that was originally added here
08-17 11:59:08.019: E/WindowManager(16460):     at android.view.ViewRoot.<init>(ViewRoot.java:263)
08-17 11:59:08.019: E/WindowManager(16460):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-17 11:59:08.019: E/WindowManager(16460):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-17 11:59:08.019: E/WindowManager(16460):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.Dialog.show(Dialog.java:241)
08-17 11:59:08.019: E/WindowManager(16460):     at sync.directtrac.NetError.showInfoMessageDialog(NetErrorPage.java:114)
08-17 11:59:08.019: E/WindowManager(16460):     at sync.directtrac.NetError.onCreate(NetErrorPage.java:26)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
08-17 11:59:08.019: E/WindowManager(16460):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-17 11:59:08.019: E/WindowManager(16460):     at android.os.Looper.loop(Looper.java:130)
08-17 11:59:08.019: E/WindowManager(16460):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-17 11:59:08.019: E/WindowManager(16460):     at java.lang.reflect.Method.invokeNative(Native Method)
08-17 11:59:08.019: E/WindowManager(16460):     at java.lang.reflect.Method.invoke(Method.java:507)
08-17 11:59:08.019: E/WindowManager(16460):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-17 11:59:08.019: E/WindowManager(16460):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-17 11:59:08.019: E/WindowManager(16460):     at dalvik.system.NativeStart.main(Native Method)

I have searched more... but i don't have any right idea to clear this.

What i want is, when loading this page, layout should be added and dialog should be shown.

Please help me to clear this error

Note: I have tried this also

@Override
    protected void onResume() {
    super.onResume();
        runOnUiThread(new Runnable() {
            public void run() {
                showInfoMessageDialog("Please check your network connection","Network Alert");
            }
        });

    }

The answer is


I got this error but it is resolved interesting. As first, i got this error at api level 17. When i call a thread (AsyncTask or others) without progress dialog then i call an other thread method again using progress dialog, i got that crash and the reason is about usage of progress dialog.

In my case, there are two results that;

  • I took show(); method of progress dialog before first thread starts then i took dismiss(); method of progress dialog before last thread ends.

So :

ProgresDialog progressDialog = new ...

//configure progressDialog 

progressDialog.show();

start firstThread {
...
}

...

start lastThread {
...
} 

//be sure to finish threads

progressDialog.dismiss();
  • This is so strange but that error has an ability about destroy itself at least for me :)

 @Override
    protected void onPostExecute(final Boolean success) {
        mProgressDialog.dismiss();
        mProgressDialog = null;

setting the value null works for me


Change this dialog.cancel(); to dialog.dismiss();

The solution is to call dismiss() on the Dialog you created in NetErrorPage.java:114 before exiting the Activity, e.g. in onPause().

Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as Context: like new ProgressDialog(this)), so it cannot be collected by the GC, causing a memory leak.


In my case finish() executed immediately after a dialog has shown.


The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.

So call

runOnUIthread(new Runnable(){

    showInfoMessageDialog("Please check your network connection","Network Alert");
});

in your OnResume function. Do not create dialogs in OnCreate
Edit:

use this

Handler h = new Handler();

h.postDelayed(new Runnable(){

        showInfoMessageDialog("Please check your network connection","Network Alert");
    },500);

in your Onresume instead of showonuithread


The way I got around this issue is by not calling intent within a dialog. **** use syntax applicable to activity or fragment accordingly

@Override
public void onClick(DialogInterface dialog, int which) {
    checkvariable= true;
    getActivity().finish();
}

@Override
public void onStop() {
    super.onStop();
    if (checkvariable) {
        startActivity(intent); 
    }
}

Please try this Way And Let me know :

Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.neterrorlayout);

   mContext=NetErrorPage.this;
   Button reload=(Button)findViewById(R.id.btnReload);
   reload.setOnClickListener(this);    
   showInfoMessageDialog("Please check your network connection","Network Alert"); 
}
public void showInfoMessageDialog(String message,String title)
{
   new AlertDialog.Builder(mContext)
   .setTitle("Network Alert");
   .setMessage(message);
   .setButton("OK",new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog,int which) 
       {   
          dialog.cancel();
       }
   })
   .show();
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to memory-leaks

AngularJS - Does $destroy remove event listeners? Implementing IDisposable correctly Best way to increase heap size in catalina.bat file If a DOM Element is removed, are its listeners also removed from memory? Resource leak: 'in' is never closed android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue This Handler class should be static or leaks might occur: IncomingHandler possible EventEmitter memory leak detected performSelector may cause a leak because its selector is unknown How can I create a memory leak in Java?

Examples related to android-alertdialog

How to use and style new AlertDialog from appCompat 22.1 and above How can I change default dialog button text color in android 5 Android simple alert dialog "android.view.WindowManager$BadTokenException: Unable to add window" on buider.show() Change the background color of a pop-up dialog AlertDialog styling - how to change style (color) of title, message, etc How can I display a list view in an Android Alert Dialog? How to dismiss AlertDialog in android How can I change the color of AlertDialog title and the color of the line under it android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue