3

I have an application which need to access context in a lot of different classes all the time, for saving and serializing data, showing dialogs etc.

According to an article on the Android developer site, this causes memory leaks: http://developer.android.com/resources/articles/avoiding-memory-leaks.html

What is the general approach for accessing context? Should a create a singelton class which holds one reference to context as soon as the app is started or what's the best approach?

Right now my methods look like this for instance

public void saveData(TheCassName classObject, Context context){
//do some stuff that involves context
}

And is called from wherever i need it.

Thanks!

Fred
  • 4,733
  • 1
  • 27
  • 47
Richard
  • 13,521
  • 9
  • 49
  • 82
  • possible duplicate of [Android - what's the difference between the various methods to get a Context?](http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context) – David Z Feb 03 '12 at 20:03

2 Answers2

3

Just to clear: There is no memory leak as context which is getting saved, is part of the application which is a process which will only get killed when the application will close.

Extend application in your app and then use the application context by making static variable in that.

public class MyApp extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }
}

You need to define application also in your manifest too.

<manifest>
  <application android:name="com.abc.MyApp">

  </application>
</manifest>
Erhannis
  • 3,613
  • 2
  • 24
  • 38
RATHI
  • 4,551
  • 7
  • 34
  • 44
  • 2
    Is this not an example of memory leaks? Since the static variable would hold a reference to the application context, it can never properly be garbage collected. Or did I understand it wrong? – Niklas Ekman Oct 19 '16 at 12:42
  • Yes, you got it all wrong. This is a correct way of holding onto application context. Due to application being a process, it's context is available as long as the process is kept alive. That's why you can't leak _this_ specific context - it just outlives everything else by framework design. – Drew Mar 14 '17 at 07:19
  • You'd be leaking memory if instead of this context you'd use an Activity as a Context. If that Activity is finished then it would be ready to be garbage collected. But, if there's somebody pointing to it then Java would keep that on memory and then you'd be generating a memory leak. – Joaquin Iurchuk Apr 26 '17 at 23:08
2

Try using application context instead of activity context. However, there are limitations on app context you should be aware of: When to call activity context OR application context?

Community
  • 1
  • 1
Peter Knego
  • 78,855
  • 10
  • 118
  • 147