首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取应用程序上下文返回null

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

Stack Overflow用户
提问于 2014-02-25 01:25:29
回答 6查看 60.6K关注 0票数 29

下面的模式被吹捧为从我的android应用程序中的任何地方获取应用程序上下文的方法。但有时执行MyApp.getContext()会返回null。我尝试通过从getContext()中删除static来更改模式,以便执行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;
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21994612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档