Android context memory leak via activity private member - android

Please clarify is code listed below would lead to context memory leak? Thanks
public class HelperClass {
private Context context;
public HelperClass(Context context) {
this.context = context;
}
public void myHelperMethod() {
// uses this.context
}
}
public class MyActivity extends Activity {
private HelperClass helper;
public void onCreate(Bundle savedInstanceState) {
helper = new HelperClass(this);
}
}

The short answer is no. What you want to beware of is a reference to the context/activity that remains after the activity has been destroyed. A device rotation is an example of an action that would cause the current activity to be destroyed by Android.
In this case, your activity is the only thing that holds a reference to your helper class. Thus when the activity is destroyed, there will be no more existing references.
If however your activity class defined the reference to the helper as a static, then that would cause a memory leak. The static reference would remain even after the activity instance was destroyed. The helper class, which holds a reference to the activity, would then prevent the activity instance from being garbaged collected.

Related

Android Studio context returning null

I have a class that's inputting some data into SharedPreferences.
private static Context context;
context = MainActivity.getContext();
sp = (SharedPreferences) context.getSharedPreferences("currentData", Context.MODE_PRIVATE).edit();
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", placeName);
editor.apply()
I set the context using a method in my MainActivity class:
public static Context getContext(){
return context;
}
However I keep getting a null object reference. Tried multiple solutions from stack overflow and can't overcome the issue.
Why is context returning null?
This is because MainActivity.getContext() is null try passing the context from MainActivity to your class.
public Context context;
public YourClass(Context context) {
this.context= context;
}
In MainActivity init it like this:-
YourClass yours = new YourClass(MainActivity.this);
And also avoid using static contexts it might cause memory leaks !!
Context is an abstract class whose implementation is provided by the
Android system
Context is provided to any Activity by the android system during runtime (Activity indirectly extends Context). You are trying to get Context from MainActivity class via static method, which will not work and will always return null:
context = MainActivity.getContext();
You should always get Context from an instance of Activity, not the class itself. You can do this easily by passing an instance of your current Activity to the constructor of your class. Then, you call getContext() on an INSTANCE of that Activity, not the Activity class itself.
Also, wanted to mention that your code is mostly anti-pattern. You should never store Context in static variables. I'd recommend you read more about Activity lifecycle in android and Context - these are fundamental knowledge.
You can get context statically throughout the application
please try below code:
In the Android Manifest file, declare the following.
<application android:name="com.xyz.MyApplication">
</application>
Use this class
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Now you can call MyApplication.getAppContext() to get your application context statically.
You are getting the context from a static method in the class, that mean that method is called before the class is actually initialized. If there is no actual instance of the activity or if the OS haven't provide with context to the activity, then is null. The Activity has access to the contexto but after the Android underlining management initialized it, the class won't have the context by it self because it is there, if you notice Activities are never instantiated using the constructor because Android does it for you.
If you want to use a static method to having a nice syntax then the static method should be inside the class that use the shared preferences and should be passed from the activity, during any method of the Activity life cycle or when the user interacts with the ui (those listeners are set on the Activity life cycle).
class MyPreferences {
static void save(String toSave, Contex context) {
//TODO your operation here
}
}
And your activity:
public class MainActivity extends AppCompatActivity {
//Below is pseudo code, be careful on doing this precisely in the activity
#Override
onCreate() {
//TODO call super and setContentView
MyPreferences.save("foo", this);
}
}
It seems your problem is you are trying to make the other class to use the Activity, but in Android is the Activity that uses other classes

Using context without any static reference

I am trying to access application resources, (string resources to be specific) from a Singleton class. Being Singleton, this class cannot hold any reference to Context objects (to prevent memory leak). While I was looking for other implementations on the net, I came across this two implementation:
Create a static context in Application class and use it across the app.
Pass context as a parameter to the method that requires it.
I don't want to use the fist one as it also uses a static reference to Context object. I understand that it's ok to have it statically in the Application class of android, but still it looks like a hack.
The second implementation is useless since i don't have any instance of context which I can pass to the someOtherMethod of the singleton.
So I came up with following implementation where I make my Singleton abstract to override its context requiring methods (for ex. getString(int resId) in the code below) when I initialize the singleton instance.
I am curious to know if this can lead to any memory leaks now?
Where am I confused with this approach:
--> The reference to context in the Overridden getString is final. I am not sure if that can cause a memory leak or not.
public abstract class SingletonClass{
.
.
.
private static SingletonClass sInstance;
private SingletonClass(Context paramContext) {
// constructor code
}
public static SingletonClass getInstance(final Context context) {
if (sInstance == null) {
sInstance = new SingletonClass(context){
#Override
public String getString(int resId) {
return context.getString(resId);
}
};
}
return sInstance;
}
public abstract String getString(int resId);
.
.
.
private void someOtherMethod(){
//uses above getString()
}
}
Your approach does have a memory leak. The first context passed into getInstance will never be garbage collected, since your anonymous class holds a reference to it. (and there is a static reference to the anonymous class). e.g., if you call getInstance(Activity), that activity will remain in memory until the process is killed!
Fortunately there is a pretty easy fix to get rid of the memory leak. You can safely hold onto the application context (context.getApplicationContext), which is basically a singleton context for lifetime of the app.
public static SingletonClass getInstance(Context c) {
if (sInstance == null) {
sInstance = new SingletonClass(c.getApplicationContext());
}
return sInstance;
}
You can depend on activity lifecycle, and require activities to pass reference to your singleton object in onResume method, and clean it in onPause.
protected void onResume() {
super.onResume();
Singleton.getInstance().onResume(this);
}
protected void onPause() {
super.onResume();
Singleton.getInstance().onPause();
}
Also, you can refresh the instance of Context and hold it in WeakReference:
class Singleton {
private WeakReference<Context> mContext;
private boolean hasContext() {
return mContext != null && mContext.get() != null;
}
public static Singleton getInstance(Context c) {
//do your singleton lazy
if (!sInstance.hasInstance()) {
sInstance.mContext = new WeakReference<>(c);
}
return sInstance;
}
}
Second case could hold a reference to finishing activity, so i don't suggest it.

Holding context, activity or views as member of a class is bad performance?

I have red somewhere that keeping views as members of an activity is bad performance, because each views is keeping a reference to its parent Context and it will fill up the heap. Is this true?
Imagine this activity:
public class MyActivity extends FragmentActivity{
private RelativeLayout mainLayout;
private LineraLayout menuLayout;
private FrameLayout tableLayout;
private Button buttonOk;
private Button buttonCancel;
#Override
protected void onCreate(Bundle bundle){
super.onCreate(bundle);
mainLayout = (RelativeLayout) findViewById(R.id.mainlayout);
// And inflating other views
}
}
And what about adapters?
public class MyAdapter extends BaseAdapter{
private MyActivity activity;
private ArrayList<MyObjects> myObjects;
public MyAdapter (MyActivity activity, ArrayList<MyObjects> myObjects){
this.activity = activity;
this.myObjects = myObjects;
}
}
Is this bad performance? Is it bad to pass an activity as a parameter instead of a Context? What if I want to access public methods from the parent MyActivity class from the adapter?
Non-Activity class
public MyDatabase{
private Context context;
private SQLiteDatabase db;
public MyDatabase(Context context){
this.context = context;
this.db = new DatabaseHelper(context).getWritableDatabase();
}
public Object getData(int id){
return db.query(params...);
}
public static class DatabseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, "my_db", null, 1);
}
}
}
Why people are saying that when a class constructor expects a Context as a parameter, you should pass getApplicationContext() instead of and Activity?
To pass Activity instance to some method or store a reference to it somewhere is a bad practice because during configuration change Android creates a new instance of an activity and old one should be removed by garbage collector. But if someone holds a reference to an old Activity object it will not be collected by GC till reference to it exists. So memory leak occurs.
But in case of adapter constructor it's fully OK to pass activity instance because adapter lifecycle is coupled to activity lifecycle. Normally it will be garbage collected after activity.
getApplicationContext returns the context of the single, global Application object of the current process so it can be used safely throughout your application code.
It's not about bad performance, but related to possible memory leak. Pass getApplicationContext() instead of Activity is just to avoid potential memory leak.
There's nothing wrong for a activity to keep views as members, since the context of the view is activity. If activity doesn't hold the references, you need to invoke findViewById each time when you want to access the view, which will really impact the performance.About the adapter, it's still ok for you to pass activity not context.
Passing Activity's context is what you need at the end to access the public methods of your Activity because in any which ways if you use getApplicationContext() you will have to cast it to your Activity during method calls.
((MainActivity)context).getMyPublicMehtods() inside the non Activity class.
And for more details #makovkastar has defined it very well. :)

Best practice to pass Context to non-activity classes?

So, my first major application is almost coded and I'm doing optimizations on my code. The app works fine, but I'm not sure about my way of passing the context to other classes. I don't want to do it the wrong way. I stumbled upon articles and questions here in Stackoverflow about contexts and which is the right way to pass it to non-activity classes. I read the documentation as well, but being a Finn makes complicated tech speak even harder to understand.
So, a simple question. Is my way of passing my main activity's context to other (helper) classes correct? If not, where can I read more about better practice on these situations.
For example:
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle sis){
super(sis);
new Helper(MyActivity.this).makeMyAppAwesome();
}
}
Helper.java
public class Helper {
Context context;
Helper(Context ctx){
this.context = ctx;
}
public void makeMyAppAwesome(){
makeBaconAndEggsWithMeltedCheese(context);
}
}
Is this OK? It would be nice if someone could provide an easy to read article with examples on this subject.
You can do that using ContextWrapper, as described here.
For example:
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
public void makeMyAppAwesome(){
makeBaconAndEggsWithMeltedCheese(this);
}
}
And call the non activity class like this from an Activity
new MyContextWrapper(this);
It is usually in your best interest to just pass the current context at the moment it is needed. Storing it in a member variable will likely lead to leaked memory, and start causing issues as you build out more Activities and Services in your app.
public void iNeedContext(Context context) {...
Also, in any class that has context, I'd recommend making a member variable for readability and searchability, rather than directly passing or (ClassName.)this. For example in MainActivity.java:
Context mContext = MainActivity.this;
Activity mActivity = MainActivity.this;
I have passed context like this which solved my problem:
public class Utils extends ContextWrapper {
private final Context context;
public Utils(Context context) {
super(context);
this.context = context;
}
public void mymethod(){}
}
super(context); with ContextWrapper helped to make getBaseContext() and getApplicationContext() valid and this.context = context; captured context in variable which I can use wherever needed in methods.
Maybe alternatively you can just opt for using a constructor with this.context = context; and replace all occurrences of getApplicationContext() and getBaseContext().
Well, an even better way is to pass context directly to the method if using only few from a class for avoiding memory leaks.
You could also create a static instance reference to your MainActivity initialized in the onCreate() method
public class MainActivity extends AppCompatActivity {
public static MainActivity mMainActivity;
#Override
private onCreate(Bundle savedInstanceState){
//...
mMainActivity = this;
}
}
and call the context like this:
MainActivity.mMainActivity;
or write a method getInstanceOf() if it's clearer and/or you prefer using an accessor
MainActivity.getInstanceOf();
This strategy might provide you with some flexibility if you decide later that you would like to call an instance method contained in your main activity like so:
MainActivity.mMainActivity.myInstanceMethod();
Just a suggestion. Criticism is welcome and encouraged.

Android : References to a Context and memory leaks

I've read that it is a mistake and a source of memory leaks in Android application to keep a long-lived references to a Context.
But I don't understand if it is ok to create a class that looks like this one:
public class HelperClass {
private Context context;
public HelperClass(Context context) {
this.context = context;
}
public void myHelperMethod() {
// uses this.context
}
}
And call it from an Activity:
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
HelperClass h = new HelperClass(this);
h.myHelperMethod();
}
...
}
This is fine, and will not cause a memory leak.
As soon as onCreate finishes executing, h will be out of scope and become eligible for garbage collection. If h was static, then you would run into problems. Only when the reference to the context outlives the lifecycle of the context itself will a memory leak occur. A few helpful hints:
Use Context.getApplicationContext() when possible. This context will live as long as your application is alive.
Be careful when using static fields and inner classes.
Run your application through a profiler to check for leaks.
The scope of the HelperClass is only within your onCreate function, so once onCreate executed, your "h" object is no longer needed and subject to garbage collection.
It would be a different story if "h" was a static member - THAT would be a great way to leak memory.

Categories

Resources