Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DialogFragment leaking memory

In the app I'm working on I'm seeing a memory leak in a DialogFragment and the only way to fix it so far has been to remove all views when the DialogFragment gets destroyed, is this a normal thing to have to do? I'm working with a custom ROM so wasn't sure if maybe that has something to do with this issue. Is there any reason NOT removing all the views from the dialog would cause them to leak memory?

    @Override
    public void onDestroyView() {
        if (getView() instanceof ViewGroup) {
            ((ViewGroup)getView()).removeAllViews();
        }
        super.onDestroyView();
    }
like image 424
mpellegr Avatar asked Apr 25 '16 14:04

mpellegr


2 Answers

This happens to my App too and I found the leak using Leakcanary.

It happens when you have a Dialog with EditText. The Blink of the Cursor, which is implemented using a callback is not handled properly when closing the View containing the EditText. And it happens by chance according to this.

https://code.google.com/p/android/issues/detail?id=188551

Edit

And this is how what I do before every dialog.dismiss():

editText.setCursorVisible(false);
dismiss();

Hope this helps!

like image 98
Jiyeh Avatar answered Oct 12 '22 11:10

Jiyeh


MemoryLeak can happen for many causes, some common causes :

  • Keep reference of your object(in this case instance of your DialogFragment) in some static fields.
  • Pass Context to Thread or AsyncTask because Threads is also GC root!
  • Your class have non-static inner class, in this case memory leak happen if inner class related to GC root (for example if inner class is instance of AsyncTask).

In your case maybe you have a view that related to GC root, while that view can not be garbage collected your dialog that keep views also can not be garbage collected.

like image 26
Mojtaba Asg Avatar answered Oct 12 '22 10:10

Mojtaba Asg