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
You can’t call
getStringbefore your Activity has been initialized. That’s becausegetStringis the same ascontext.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:
Then create
MyApplication.javafile:And then use it to get string resource:
You can even do this fir static fields.