0

I am trying to make a string array in Android... this works:

String titles[] = { "Matches", "Players" };

This does not:

String titles[] = { getString(R.string.matches), getString(R.string.players) };

How can I do what I'm trying to do?

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

3
  • We'd need a little bit more context. At the point where you're doing this, is there a fully-constructed Activity or Context instance available? Commented Jan 31, 2016 at 2:08
  • please edit your post to include more details, like the exact error you see. Commented Jan 31, 2016 at 2:13
  • Added the error... it doesnt matter if I put it after the Context or not... still the same error. Commented Jan 31, 2016 at 2:15

2 Answers 2

2

You are probably trying to initialize your String[] as a class field and that is not allowed because you cannot yet access resources as shown in the exception.

Move the assignment into your onCreate method and it will work.

private String[] titles;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ....
    titles = new String[] { getString(R.string.matches), getString(R.string.players) };
    ....
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

String titles[] = { getResources().getString(R.string.matches), getResources().getString(R.string.players) };

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.