In my project I have this situation. This is a part of my MainActivity
, I have initialized the object helperClass
with the applicationContext
and made it static because I have to use it in the OnClickListener
of a button:
public class MainActivity {
public static HelperClass helperClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
helperClass = new HelperClass(getApplicationContext());
{...}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
helperClass.doSomething();
}
});
}
}
This is a part of the helper class, I need the context because I have to store some data in the app memory:
public class HelperClass{
private Context context;
public HelperClass(Context context) {
this.context = context;
}
public void doSomething() {
File file = new File(context.getFilesDir(), "name");
{...}
}
}
Now, this code works, but when I declare helperClass
static there is a warning saying this is a memory leak; I tried to remove the context from the HelperClass
but I could not retrieve the context from the class; I also tried to remove the static declaration but I need it because the OnClickListener
is a static context.
I read here that I can use ApplicationContext
, it is ok but it's an old article.
Is there a better solution?
You do not need to make a field static in order to use it in the Listener. Moreover, you shouldn't, as you correctly said that it may lead to a memory leak :-) Just remove the static keyword, run the code and it will work ^^
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments