获取应用程序上下文返回null

lea*_*ner 26 android applicationcontext

以下架构被吹捧为从我的Android应用程序中的任何位置获取应用程序上下文的方式.但有时候MyApp.getContext()返回null.我尝试通过删除static来改变模式,getContext()以便我这样做MyApp.getInstance().getContext().它仍然返回null.我该如何解决?如何从我的应用程序中的任何位置获取应用程序的上下文?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*sys 45

在()onCreate()的实例中创建,然后 从应用程序的任何位置调用,您将静态获取应用程序上下文.getApplicationContext()mContextMyApp.getContext()

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();    
    }
}
Run Code Online (Sandbox Code Playgroud)

记得申报你的 AndroidManifest.xml

<application android:name="com.mypackage.mypackage.MyApp">
...
...
...
</application>
Run Code Online (Sandbox Code Playgroud)

  • 该链接解决了我的问题.我错过了`<application android:name ="com.xyz.MyApplication">`.谢谢. (12认同)
  • 由于垃圾收集器,你的静态引用可能在一段时间后为null ... (5认同)
  • @learner,你的评论节省了很多时间!谢谢. (2认同)
  • 我收到此警告“不要将 Android 上下文类放在静态字段中;这是内存泄漏”,我该如何解决此问题? (2认同)

Sam*_*awy 10

创建的一个静态实例Context在你OnCreate并保持它,直到你想从一个getter方法得到它getContext()

来自Application班级:

public class MyApp extends Application {

private static Context sContext;
@Override
public void onCreate() {
    sContext = getApplicationContext();
    super.onCreate();
}

public static Context getContext() {
    return sContext;
}
}
Run Code Online (Sandbox Code Playgroud)

在你的声明中声明Manifest:

<application android:name="com.package.name.MyApp">
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的帮助.+1.我错过了`<application android:name ="com.xyz.MyApplication">` (2认同)