Jack Hack
Jack Hack

Reputation: 111

This Field leaks context object

I am using Context object inside non-Activity, it is working perfectly but the problem is it shows warning

That is where I am using the context object enter image description here

Here is the result of inspection enter image description here

Upvotes: 10

Views: 7092

Answers (1)

Evstropov V
Evstropov V

Reputation: 520

You can use WeakReferences for this case. something like this:

public class ContactsTask {

    private WeakReference<Context> weakContext;

    public ContactsTask(Context context){
        weakContext = new WeakReference<>(context);
    }

    public void doSomething(){
        if (weakContext!=null) weakContext.get() ...    //return context without leaks
    }

}

Upvotes: 20

Related Questions