Strange NullPointerException

a 夏天 提交于 2019-12-12 22:14:47

问题


I have strange problem...

My file strings.xml contains:

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

Well, my R contains:

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

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

at {the line where I instanciate the building_name}

What's wrong with my code?Please help


回答1:


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.

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>

Then create MyApplication.java file:

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.




回答2:


Using this might help you

getResources().getString(R.string.building_name);

This works for me




回答3:


There are some cases where this happens, for the same you should try some steps mentioned below:

  1. Try to clean your project.
  2. Check whether the android.R class file is imported or not, if it is imported then remove it and import your R class file.
  3. Try using getResources().getString(R.string.myString) method.


来源:https://stackoverflow.com/questions/6261990/strange-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!