Strange NullPointerException

android, nullpointerexception, runtimeexception

Solution

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.

Problem

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

Original source