Reputation: 21
I have the following 2 lines of code in my MainActivity class passing a value:
RecyclerView mRecyclerView = findViewById(R.id.act_recyclerview);
new LoadText(this,mRecyclerView).execute();
In my LoadText class, I am consuming as follows:
private Context mContext;
private RecyclerView mRecyclerView;
public LoadText(Context context, RecyclerView recyclerView){
this.mContext=context;
this.mRecyclerView=recyclerView;
}
My code works fine, however Android Studio is warning of a resource leak when I hover over mContext and mRecyclerView. I have looked for solutions to similar problems like mine and it was suggested to pass the value via a constructor, which is what I am doing so I am not sure I understand why.
Upvotes: 1
Views: 2549
Reputation: 54234
This is a warning, which means that the system knows that something might be wrong, but can't say 100% for sure.
In this case, the question is how long your LoadText
object lives for. If it lives longer than the Activity
or the RecyclerView
that you pass to it, your code will cause a memory leak: the LoadText has a strong reference to the Activity, which will prevent it from being garbage collected.
If you, as a human, know that your LoadText
object will never live longer than the Activity (or will only do so for a brief amount of time), then you can safely ignore this warning. If, on the other hand, the LoadText
object lives for a long time, it could potentially keep your activity alive forever.
Practically speaking, leaking a single Activity isn't the end of the world. But if you do things like this a lot, eventually your app will run out of memory and crash.
It's also possible that the zombie Activity will wind up executing code that you don't expect (maybe the LoadText class calls a method on it), which could lead to undesirable behavior or a crash.
Upvotes: 3