-1

In the onPostExecute i am trying to show the handler but it giving the exception Activity has leaked window. The error point is highlighted below on the code. What is the solution to this problem.

 class Communicator extends AsyncTask<String, String, String> 
            {
                int prog = 0;

                @Override
                protected String doInBackground(String... params) {
                    String response = null;
                    try {
                        if(Login.uname != null && Login.pass != null){
                        sync(Login.uname, Login.pass);
                        }else if(SplashScreen.user != null && SplashScreen.pas != null){
                            sync(SplashScreen.user, SplashScreen.pas);
                        }
                        if("ok".equalsIgnoreCase(status))
                        {
                            if(memoryInfo(true)){
                                AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
                                alert.setTitle(R.string.set4Play);
                                alert.setMessage(getString(R.string.lowMemorySync));
                                alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                                alert.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                                alert.setCanceledOnTouchOutside(false);
                                alert.show();
                            }else{
                            new Thread()
                            {   
                                @Override 
                                public void run()
                                {
                                    try{
                                    Data.filenames = new ArrayList<String>(); 
                                    for(int i = 0; i< list.size();i++)
                                    {
                                        if(mname.size() > i)
                                            mnam = mname.get(i);
                                        if(Login.uname != null && Login.pass != null){
                                            mp3Download(Login.uname, Login.pass, list.get(i), mnam);
                                        }
                                        if(SettingActivity.userna != null && SettingActivity.passwo != null){
                                            mp3Download(SettingActivity.userna, SettingActivity.passwo, list.get(i), mnam);
                                        }
                                        publishProgress("" + ((bytecopied1*100)/(totalsize)));
                                        c++;
                                        long b = bytecopied1*100;
                                        float a = b/totalsize;
                                        Message msg = my_handler.obtainMessage();
                                        msg.arg1 = (int)a;
                                        my_handler.sendMessage(msg);
                                        if(list.size() == c){
                                            isTrue = true;
                                        }
                                    }
                                    }catch (Exception e) {

                                    }
                                    super.run(); 
                                }
                            }.start();
                            }
                            count ++;
                        }
                        else if("tomany".equalsIgnoreCase(status))
                        {
                            AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
                            alert.setTitle(R.string.set4Play);
                            alert.setMessage(getString(R.string.tomany));
                            alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                            alert.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                            alert.setCanceledOnTouchOutside(false);
                            alert.show();
                        }
                        else if("fail".equalsIgnoreCase(status))
                        {
                            AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
                            alert.setTitle(R.string.set4Play);
                            alert.setMessage(getString(R.string.connectionerror));
                            alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                            alert.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent backintent = new Intent(NeliteMusicActivity.this, HomeScreen.class);
                                    startActivity(backintent);
                                    return;
                                }
                            });
                            alert.setCanceledOnTouchOutside(false);
                            alert.show();
                        }
                        totalsize = 0;
                        for(int i=0; i<list.size(); i++)
                        {
                            totalsize += Integer.parseInt(cont.get(i).getSize()); 
                        }

                    } catch (Exception e) {
                        Log.e("Data.LOG", e.getMessage(), e);

                    } finally {
                    }
                    return response;
                }

                @Override
                protected void onPreExecute() {
                    prog = 0;
                    super.onPreExecute();
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);

                    if ("ok".equalsIgnoreCase(status)) 
                    {
                        sizekb=0;
                        new Set4Play13(getBaseContext());
                        sizeall =  new Integer[cont.size()];
                        for (int i = 0; i < cont.size(); i++) {
                            mixname = cont.get(i).getMixname();
                            mixnumber = cont.get(i).getNumber();
                            int size = Integer.parseInt(cont.get(i).getSize());

                             sizekb= sizekb+size;
                             sizeall[i] = size;

                            db.addContact(new Dataset(cont.get(i).getNumber(), cont
                                    .get(i).getUsername(), cont.get(i).getMixname(),
                                    cont.get(i).getSize(), cont.get(i).getUpdate(),
                                    cont.get(i).getKg()));
                            Log.e("cont.get(i).getKg()", "cont.get(i).getKg()"+cont.get(i).getKg());
                        }
                    }
                }

                private Handler my_handler = new Handler() 
                {

                    public void handleMessage(Message msg) 
                    {
                        int a=msg.arg1;
                        progress.setProgress(a);
                        textsync.setText("Syncing mix "+c);
                        if(progress.getMax()<=a)
                        {
                            if (isOnline()) 
                                {
                                    AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
                                    alert.setTitle(R.string.set4Play);
                                    alert.setMessage(getString(R.string.updatedMix));
                                    alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                                    alert.setButton(getString(R.string.ok), 
                                            new DialogInterface.OnClickListener() 
                                    {
                                          public void onClick(DialogInterface dialog, int which) {
                                              dialog.dismiss();
                                              animatedStartActivity();
                                        }
                                        });
                                    alert.setCanceledOnTouchOutside(false);
                                    alert.show();(Here is the Error)
                                }
                            if (!isOnline()) {
                                AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
                                alert.setTitle(R.string.set4Play);
                                alert.setMessage(getString(R.string.connectionerror));
                                alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                                alert.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                      public void onClick(DialogInterface dialog, int which) {
                                           Intent intent = new Intent(getApplicationContext(),HomeScreen.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            startActivity(intent);
                            finish();
                                    } 
                                    }); 
                                alert.setCanceledOnTouchOutside(false);
                                alert.show();
                            }
                        }
                        super.handleMessage(msg);
                    }
                };
            }

Logcat:

10-13 18:53:20.220: E/WindowManager(4530): Activity com.nelitemusic.NeliteMusicActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40c2d8f8 that was originally added here
10-13 18:53:20.220: E/WindowManager(4530): android.view.WindowLeaked: Activity com.nelitemusic.NeliteMusicActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40c2d8f8 that was originally added here
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.ViewRoot.<init>(ViewRoot.java:291)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:249)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:193)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:118)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.Window$LocalWindowManager.addView(Window.java:532)
10-13 18:53:20.220: E/WindowManager(4530):  at android.app.Dialog.show(Dialog.java:269)
10-13 18:53:20.220: E/WindowManager(4530):  at com.nelitemusic.NeliteMusicActivity$Communicator$1.handleMessage(NeliteMusicActivity.java:372)
10-13 18:53:20.220: E/WindowManager(4530):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 18:53:20.220: E/WindowManager(4530):  at android.os.Looper.loop(Looper.java:132)
10-13 18:53:20.220: E/WindowManager(4530):  at android.app.ActivityThread.main(ActivityThread.java:4126)
10-13 18:53:20.220: E/WindowManager(4530):  at java.lang.reflect.Method.invokeNative(Native Method)
10-13 18:53:20.220: E/WindowManager(4530):  at java.lang.reflect.Method.invoke(Method.java:491)
10-13 18:53:20.220: E/WindowManager(4530):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
10-13 18:53:20.220: E/WindowManager(4530):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
10-13 18:53:20.220: E/WindowManager(4530):  at dalvik.system.NativeStart.main(Native Method)
10-13 18:53:20.220: E/WindowManager(4530): Activity com.nelitemusic.NeliteMusicActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40b35838 that was originally added here
10-13 18:53:20.220: E/WindowManager(4530): android.view.WindowLeaked: Activity com.nelitemusic.NeliteMusicActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40b35838 that was originally added here
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.ViewRoot.<init>(ViewRoot.java:291)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:249)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:193)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:118)
10-13 18:53:20.220: E/WindowManager(4530):  at android.view.Window$LocalWindowManager.addView(Window.java:532)
10-13 18:53:20.220: E/WindowManager(4530):  at android.app.Dialog.show(Dialog.java:269)
10-13 18:53:20.220: E/WindowManager(4530):  at com.nelitemusic.NeliteMusicActivity$Communicator$1.handleMessage(NeliteMusicActivity.java:372)
10-13 18:53:20.220: E/WindowManager(4530):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 18:53:20.220: E/WindowManager(4530):  at android.os.Looper.loop(Looper.java:132)
10-13 18:53:20.220: E/WindowManager(4530):  at android.app.ActivityThread.main(ActivityThread.java:4126)
10-13 18:53:20.220: E/WindowManager(4530):  at java.lang.reflect.Method.invokeNative(Native Method)
10-13 18:53:20.220: E/WindowManager(4530):  at java.lang.reflect.Method.invoke(Method.java:491)
10-13 18:53:20.220: E/WindowManager(4530):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
10-13 18:53:20.220: E/WindowManager(4530):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
10-13 18:53:20.220: E/WindowManager(4530):  at dalvik.system.NativeStart.main(Native Method)
10-13 18:53:20.720: E/<<path>>(4530): >>path<<file://mnt/sdcard/NeliteMusic/sponsormix.mp3
10-13 18:53:20.720: E/<<Login Start>>(4530): >>Login Start<<
10-13 18:53:21.100: E/<<path>>(4530): >>path<<file://mnt/sdcard/NeliteMusic/sponsormix.mp3
10-13 18:53:21.100: E/<<SettingActivity Start>>(4530): >>SettingActivity Start<<
bkshukla
  • 179
  • 5
  • 19
  • Asynctask doInBackground(Params...) involves non UI threads to execute tasks, hence invoking UI executions will produce exception. In your case you need to go for http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...) – code-jaff Aug 13 '12 at 14:00
  • 10-13 18:53:20.220: E/WindowManager(4530): at com.nelitemusic.NeliteMusicActivity$Communicator$1.handleMessage(NeliteMusicActivity.java:372) <- can you point out this line? – Ostkontentitan Aug 13 '12 at 14:03
  • you are doing way too many ui operations in doinbackground, You should not show alert dialogs from this thread – nandeesh Aug 13 '12 at 14:04
  • com.nelitemusic.NeliteMusicActivity$Communicator$1.handleMessage(NeliteMusicActi‌​vity.java:372) Points to ==> if (isOnline()) { ///// alert.show();} – bkshukla Aug 13 '12 at 14:07

3 Answers3

1

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

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).
Community
  • 1
  • 1
Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
  • I have tried the 1st point but its not working rather it gives the same error.Can you elaborate the 2nd point Please ? – bkshukla Aug 13 '12 at 14:27
  • For the second suggestion, you could try displaying your alert on a new thread using a Runnable. runOnUiThread(new Runnable() { public void run() { MyDialog.Prompt(NameOfYourActivity.this); } }); – Kyle Clegg Aug 13 '12 at 14:32
0

Try using a DialogFragment instead of just a Dialog. They handle the lifecycle better.

Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64
0

Ok, let me give some basic idea to show dialog boxes while update,

class Communicator extends AsyncTask<String, Integer, String> 
{
    int prog = 0;

    @Override
    protected String doInBackground(String... params) {
        String response = null;
        try {
            if(Login.uname != null && Login.pass != null){
            sync(Login.uname, Login.pass);
            }else if(SplashScreen.user != null && SplashScreen.pas != null){
                sync(SplashScreen.user, SplashScreen.pas);
            }
            if("ok".equalsIgnoreCase(status))
            {
                if(memoryInfo(true)){
                    publishProgress(LOW_MEMORY);
                    return (null);
                }else{.....

For showing the dialog

protected void onProgressUpdate(Integer... statusCode) {
    switch (statusCode[0]) {
    case LOW_MEMORY:
        AlertDialog alert =new AlertDialog.Builder(NeliteMusicActivity.this).create();
        alert.setTitle(R.string.set4Play);
        alert.setMessage(getString(R.string.lowMemorySync));
        alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        alert.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alert.dismiss();
            }
        });
        alert.setCanceledOnTouchOutside(false);
        alert.show();
        break;
    }
}

Hope this will make sense

code-jaff
  • 9,230
  • 4
  • 35
  • 56