1

I'm trying to reference a few strings that I've stored in an xml. I'm getting this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 
'android.content.res.Resourcesandroid.content.Context.getResources()' 
on a null object reference at
android.content.ContextWrapper.getResources(ContextWrapper.java:86)

on the line where I'm using getString to reference the variable from xml.

Line where I see the error:

private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);

Full error:

com.android.example.helloworld E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android.example.helloworld, PID: 8408
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.example.helloworld/com.android.example.helloworld.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
    at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
    at android.content.Context.getString(Context.java:377)
    at com.android.example.helloworld.MainActivity.<init>(MainActivity.java:55)
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at java.lang.Class.newInstance(Class.java:1606)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

My /res/values/variables.xml file:

<string name="MY_CLIENT_ID">foo1</string>
<string name="MY_CLIENT_SECRET">bar1</string>

My AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Hello!"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="CLIENT_ID"
        android:value="@string/MY_CLIENT_ID" />
    <meta-data
        android:name="CLIENT_SECRET"
        android:value="@string/MY_CLIENT_SECRET" />

    <activity
        android:name="com.android.example.helloworld.MainActivity"
        android:label="Hello!" >
        <intent-filter android:label="@string/app_name" >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

My partial code for MainActivity.java file:

public class MainActivity extends ActionBarActivity implements myListener  {

/* One of the very first lines that are executed throw the nullpointerexception */

    private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);
    private String CLIENT_SECRET = getString(R.string.MY_CLIENT_SECRET);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        temp = (TextView) findViewById(R.id.temp);

        obj = new foo(CLIENT_ID, CLIENT_SECRET, this);
        obj.bar()
    }
}

Here's what I've done so far.

1) I'm using http://developer.android.com/guide/topics/resources/string-resource.html as a reference.

2) If I hardcode the values in the beginning and run the app it works. I only get the said error when I try to reference the values from xml.

3) I have searched quite a bit on this topic on google and stackexchange and have tried several approaches suggested on the stackexchange links such as:

  • creating and calling a method like below. I get that same error inside this method.

    public String getStringResourceByName(String resourceName) {
        String packageName = "com.android.example.helloworld";
        Log.i("-- package name --",packageName);
        int resId = this.getResources().getIdentifier(resourceName, "string", packageName);
        String resName = getString(resId);
        Log.i("-- resource name -- ",resName);
        return resName;
    }
    
  • Using MainActivity.this specifically in the above method

    public String getStringResourceByName(String resourceName) {
        String packageName = "com.android.example.helloworld";
        Log.i("-- package name --",packageName);
        int resId = MainActivity.this.getResources().getIdentifier(resourceName, "string", packageName);
        String resName = getString(resId);
        Log.i("-- resource name -- ",resName);
        return resName;
     }
    

    All of the changes throw the same error back at me.


Can someone guide me on what am I missing here? I hope I've provided with sufficient data.

1
  • 2
    Your Activity has not been created yet, therefore you still don't have a valid context. Move the calls to onCreate() Commented Jul 20, 2015 at 14:01

2 Answers 2

4
private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);

If you initialize the field on class initialization, you are calling getString() before onCreate(), and thus the Context has not initialized. Better use it like this

public void onCreate(final Bundle bundle) {
    // Other code    
    CLIENT_ID = getString(R.string.MY_CLIENT_ID);
}

Also I strongly advise against caching the strings, because you can get wrong translations if the language has changed (this problem already happened to me so I say this from experience). Instead, use getString() whenever you need it.

Sign up to request clarification or add additional context in comments.

Comments

0

You need a Context to access your app resources. You're trying to get a resource without having a valid context first. Move your calls to onCreate() method, where your Activity is first created and you have the context:

private String CLIENT_ID;
private String CLIENT_SECRET;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    temp = (TextView) findViewById(R.id.temp);
    CLIENT_ID = getString(R.string.MY_CLIENT_ID);
    CLIENT_SECRET = getString(R.string.MY_CLIENT_SECRET);

    obj = new foo(CLIENT_ID, CLIENT_SECRET, this);
    obj.bar()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.