Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

android - How to pass context to a module classes without using a static context?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace

MyApplication.context = getApplicationContext();

With

MyApplication.context = this;

And you need to add the application name to the manifest for this Context to ever be set

However, if you have a core Java library, you should not be using an Application because you have no life cycle methods to handle. Just define methods that use Context objects, import your library externally, and use Application Context sparingly if you're actually in an Activity, Service, or other Context subclass


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...