调用 context.getResources() 返回 null [英] Calling context.getResources() returns null

查看:63
本文介绍了调用 context.getResources() 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在我的项目中获取一个字符串资源,但是当我调用 context.getResources().getString(...) 时,我得到一个 NullPointerException.在调试模式下,我发现上下文不为空,但查看其成员,我发现 mResources 为空.为什么没有为活动上下文加载资源?

So I am trying to get a string resource in my project but when I called context.getResources().getString(...), I get a NullPointerException. In debug mode, I found out that the context isn't null but looking at its members, I found out that mResources was null. Why are the resources not loaded for the activity context?

编辑

显然,这就是触发异常的原因

Apparently, this is what triggered the Exception

public class MyActivity extends Activity {

    SomeClass someClass = new SomeClass(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}


public class SomeClass {

    private final Context mContext;

    public SomeClass(Context context) {
        mContext = context;
        mContext.getResources().getString(R.string.app_name);
    }
}

我不得不按照 CommonsWare.谢谢.

I had to move the initialization of someClass to after super.onCreate() as suggested by CommonsWare. Thanks.

推荐答案

如果非要我猜的话,您正试图在初始化程序中调用它.在您的活动中的 super.onCreate() 调用返回之前,不要尝试使用 getResources().

If I had to guess, you are trying to call this in an initializer. Do not attempt to use getResources() before the super.onCreate() call in your activity returns.

这篇关于调用 context.getResources() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆