Kingsolmn
Kingsolmn

Reputation: 1858

Problems with calling from strings.xml

I am having a problem calling string values from the strings.xml resource in Android. The strings.xml file is below:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="name1">contact_name1</string>
    <string name="phone1">contact_phone1</string>
</resources>

And the code calling for the string values is:

private final String NAME1  = getString(R.string.name1);
private final String PHONE1 = getString(R.string.phone1);

I am calling for the strings from my main.java where I extend Activity, so I have the context. The problem is that when I run the app (physical device (EVO) or an emulator (API Levels 5 - 8) I get a NullPointerException at the line where the first getString() call is located. I have been over Google's documentation, a number of posts here and at AndDev.org with no change to the end result. Will some one please tell me whats wrong before I pull all of my hair out!? The strings.xml file is in the standard location (<project_folder><res><values> directory) in the same package as the rest of the app.

Upvotes: 1

Views: 4596

Answers (2)

Pinki
Pinki

Reputation: 21919

use the below line in onCreate()

final String NAME1  = (getResources().getString(R.string.name1));

Upvotes: 1

techi.services
techi.services

Reputation: 8533

You can't call getString from what is in effect the constructor of an Activity as the context does not exist. You will need to remove the final keyword and assign the member variables in onCreate().

Upvotes: 6

Related Questions