1

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?

1
  • 1
    Where you placed that statement? in Declaration? Commented Jun 20, 2012 at 0:17

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+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.
0

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(...);

1 Comment

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.

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.