Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This Field leaks context object

Tags:

android

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

like image 797
Jack Hack Avatar asked Jan 22 '18 12:01

Jack Hack


1 Answers

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
    }

}
like image 187
Evstropov V Avatar answered Nov 13 '22 02:11

Evstropov V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!