问题
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:
- Try to clean your project.
- Check whether the android.R class file is imported or not, if it is imported then remove it and import your R class file.
- Try using getResources().getString(R.string.myString) method.
来源:https://stackoverflow.com/questions/6261990/strange-nullpointerexception