Search code examples
androidmemory-leaksandroid-popupwindow

How to fix Android application leaked resources


I have following code in my Activity:-

public void showPopup(View view) {
    View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
    PopupWindow popupWindow = new PopupWindow(popupView,
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
    // Example: If you have a TextView inside `popup_layout.xml`
    ImageView imageView = (ImageView) popupView.findViewById(R.id.popupImageView);
    if (mImagePath != null) {
        if (Utility.fileExist(mImagePath)) {
            imageView.setImageBitmap(BitmapFactory.decodeFile(mImagePath));
        } else {
            Toast.makeText(this, "Image not found!", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, "Image not found!", Toast.LENGTH_LONG).show();
    }

    popupWindow.setFocusable(true);

    popupWindow.setBackgroundDrawable(new ColorDrawable());
    int location[] = new int[2];

    view.getLocationOnScreen(location);

    popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
            location[0], location[1] + view.getHeight());
}

When screen rotates I get following error. Could you inform how to fix this error:-

08-13 16:04:08.358  20827-20827/com.app.locationnote E/WindowManager﹕ Activity com.app.locationnote.NoteEditor has leaked window android.widget.PopupWindow$PopupViewContainer@4274ad80 that was originally added here
android.view.WindowLeaked: Activity com.masum.locationnote.NoteEditor has leaked window android.widget.PopupWindow$PopupViewContainer@4274ad80 that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
        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)

Solution

  • You can close your popup in Activity.onDestroy() method:

     if (popupWindow.isShowing()) {
         popupWindow.dismiss();
    }