Get application context returns null

后端 未结 6 906
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 18:49

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 n

6条回答
  •  自闭症患者
    2020-11-27 19:27

    Create a static instance of the Context in your OnCreate and keep it till you want to get it from a getter method getContext()

    From the Application class:

    public class MyApp extends Application {
    
    private static Context sContext;
    @Override
    public void onCreate() {
        sContext = getApplicationContext();
        super.onCreate();
    }
    
    public static Context getContext() {
        return sContext;
    }
    }
    

    Declare it in your Manifest:

    
    

提交回复
热议问题