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; } }
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With