奇怪的NullPointerException [英] Strange NullPointerException

查看:123
本文介绍了奇怪的NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有奇怪的问题...

I have strange problem...

我的文件strings.xml中包含:

My file strings.xml contains:

<?xml version="1.0" encoding="utf-8?>
<resources>
    <string name="building_name">My House</string>
</resources>

好吧,我的R含有:

Well, my R contains:

[...]
public static final class String {
    public static final int building_name=0x7f02383;
}
[...]

所以,当我尝试调用此字符串我的code是这样的:

So, when I try to call this String in my code like this:

private final String BUILDING_NAME = getString(R.string.building_name);

我有这样的错误:

I have this error:

java.lang.RuntimeException: Unable to instanciate activity ComponentInfo{...}:          java.lang.NullPointerException
{...}
  caused by: java.lang.NullPointerException

在{在我实例化的building_name行}

at {the line where I instanciate the building_name}

这有什么错我的code吗?请帮

What's wrong with my code?Please help

推荐答案

您不能调用的getString 在你的活动已被初始化。这是因为的getString 相同 context.getResources()的getString()。和上下文未初始化。

You can't call getString before your Activity has been initialized. That's because getString is the same as context.getResources().getString(). And context is not initialized.

所以基本上,你不能用这种方式将值分配给静态变量。

So basically, you can not assign value to static variables in this way.

但是,在您的静态变量使用资源字符串的方法。对于这个创建应用程序(请参见并的this ),然后从那里获取上下文。下面是一个简单的例子:

But there is a way to use resource strings in your static variables. For this create your application (see this and this) and then retrieve context from there. Here is a short example:

<manifest ...>
    ...
    <application  android:name="com.mypackage.MyApplication" ... >
       ...
    </application>
    ...
</manifest>

然后创建 MyApplication.java 文件:

public class MyApplication extends Application 
{   
    private static MyApplication s_instance;

    public MyApplication ()
    {
        s_instance = this;
    }

    public static Context getContext()
    {
        return s_instance;
    }

    public static String getString(int resId)
    {
        return getContext().getString(resId);       
    }
}

,然后用它来获得字符串资源:

And then use it to get string resource:

private final String BUILDING_NAME = MyApplication.getString(R.string.building_name);

您甚至可以做到这一点杉静态字段。

You can even do this fir static fields.

这篇关于奇怪的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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