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

查看:398
本文介绍了调用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);
    }
}

我必须按照 CommonWare 的建议将someClass的初始化移动到super.onCreate()之后.谢谢.

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天全站免登陆