Jason Axelrod
Jason Axelrod

Reputation: 7805

Android Initializing a String[] with getString values?

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

Upvotes: 0

Views: 90

Answers (2)

George Mulligan
George Mulligan

Reputation: 11903

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

Upvotes: 2

mikebrsv
mikebrsv

Reputation: 1960

Try this:

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

Upvotes: 0

Related Questions