Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get application context returns null

The following schema has been touted as the way to get application context from anywhere within my android app. But sometimes doing MyApp.getContext() returns null. I tried changing the schema by removing static from getContext() so that I would do MyApp.getInstance().getContext(). It still returns null. How do I fix this? How do I get my application's context from anywhere within my app?

public class MyApp extends Application {     private static MyApp instance;      public static MyApp getInstance() {         return instance;     }      public static Context getContext() {         return instance.getApplicationContext();     }      @Override     public void onCreate() {         super.onCreate();         instance = this;     } } 
like image 768
learner Avatar asked Feb 24 '14 17:02

learner


1 Answers

Create in onCreate() an instance of getApplicationContext() (mContext) then call MyApp.getContext() from everywhere in your app and you will get your application context statically.

public class MyApp extends Application {  //private static MyApp instance;  private static Context mContext;      public static MyApp getInstance() {         return instance;     }      public static Context getContext() {       //  return instance.getApplicationContext();       return mContext;     }      @Override     public void onCreate() {         super.onCreate();     //  instance = this;      mContext = getApplicationContext();         } } 

Remember to declare into your AndroidManifest.xml

<application android:name="com.mypackage.mypackage.MyApp"> ... ... ... </application> 
like image 80
Jorgesys Avatar answered Sep 16 '22 21:09

Jorgesys