Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using this code to pull my string array from my values folder:

String achievementNames[] = getResources().getStringArray(R.array.achieveString);
    String achievementDescriptions[] = getResources().getStringArray(R.array.achieveDescript);

However, when I run this, it gives me a null pointer exception on those lines of code. Is there a better way to pull string arrays or is there an error in my code?

share|improve this question
1  
Where you placed that statement? in Declaration? – user948620 Jun 20 '12 at 0:17

2 Answers

up vote 2 down vote accepted

You shouldn't call getResources() unless onCreate() callback has been triggered.

public class StackStackActivity extends Activity 
{

    String[] myArray = getResources().getStringArray(R.array.glenns); // This returns null

    public StackStackActivity()
    {

        myArray = getResources().getStringArray(R.array.glenns); // This returns null also
    }

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myArray = getResources().getStringArray(R.array.glenns); // Returns an array from resources
    }
}
share|improve this answer
1  
+1 for identifying what is most likely the source of OP's problem. However, it should be clarified that there's no need to call setContentView before retrieving resources. In fact, sometimes there are reasons to defer any calls to setContentView until after onCreate. – Ted Hopp Jun 20 '12 at 0:34
Ah, you have a point :) – user948620 Jun 20 '12 at 0:38

Make sure you pass a Context object to wherever you call this method from (as my guess is that getResources() is returning null). With this Context object, you can call,

context.getResources().getStringArray(...);
share|improve this answer
Same error persists. Any other ideas? – rphello101 Jun 20 '12 at 0:30
Yeah... post more information. i.e. the code that surrounds those two lines, the logcat, the line number where the NullPointerException occurs, etc. There's not much left to tell from the info you've given us. – Alex Lockwood Jun 20 '12 at 0:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.