user2386226
user2386226

Reputation:

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!

Upvotes: 1

Views: 2418

Answers (2)

Moonbloom
Moonbloom

Reputation: 7928

You should never ever ever ever EVER hold a static reference to a Context.

WHY do you need to hold a static reference to a fragment? If you answer that, then we can guide you on how to avoid it.

Static references never die, and that fragment context is most likely linked to an Activity context at some point, which means that ALL those elements can never ever be garbage collected. This is really bad.

Upvotes: 1

Anton Potapov
Anton Potapov

Reputation: 1275

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();
    }
}

Upvotes: 9

Related Questions