I have created a library, and added as a module in my app. My library does not have any activity class
, all classes are core java classes, so i don't have access to context
.
This is what i did;
- My library class is
singleton
- I have created a static variable like this;
static Context myGlobalContext
- I created a method where i set this context;
public void init(Context context){
myGlobalContext=context;
}
I set this context from the first activity;
MyClass.sharedInstance().init(MyApplication.getAppContext());
then i use this myGlobalContext
in all of the library classes.
This thing works fine when i debug this, the value of myGlobalContext
is never null, but i am getting some crashes from crashlytics, where context
is null.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)'
on a null object reference
When i run lint
, it also warns about the static global context
This is my application class
, here i create context;
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…