Search code examples
androidandroid-fragmentsmemory-leaksandroid-contextandroid-memory

How do I avoid a memory leak from a static fragment context?


I keep getting a warning for a memory leak for my static fragment instance. I declare it as follows:

private static myFragment thisFragment;

and call it here:

public static myFragment newInstance() {

        if (thisFragment == null) {
            thisFragment = new myFragment();
        }
        return thisFragment;
    }

How do I fix this? any ideas?

Thanks!


Solution

  • Well, there are 3 possible solutions:

    1) Not creating static Fragments. They are always bound to the context, so, they shouldn't be static. Consider refactoring your app architecture.

    2) Setting fragment instance to null when context is destroyed (activity onStop)

    3) Using WeakReference for fragment field which will not hold the instance from GC.

    UPD: Example for 3)

    class ExampleFragment extends Fragment {
    
        private static WeakReference<Fragment> instance;
    
        public static ExampleFragment getInstance() {
            if (instance == null) {
                instance = new WeakReference<>(new ExampleFragment());
            }
            return instance.get();
        }
    }