Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access context from anywhere? Global context?

Tags:

android

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!

like image 901
Richard Avatar asked Oct 26 '25 16:10

Richard


2 Answers

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>
like image 99
RATHI Avatar answered Oct 28 '25 06:10

RATHI


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?

like image 34
Peter Knego Avatar answered Oct 28 '25 08:10

Peter Knego