How to load xml resources to Activity field

173 views Asked by At

What I did is

public class MainActivity extends Activity {

    private final String[] types = { "s1", "s2", "s3" };

But I want to keep those values in res/values/types.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array
        name="types">
            <item>s1</item>
            <item>s2</item>
            <item>s3</item>
    </string-array>
</resources>

So I changed to

public class MainActivity extends Activity {

    private final String[] types = getResources().getStringArray(R.array.types);

But I get exception when app starts

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

So I suppose the only solution is to load that array in onCreate? If so then after Activity recreation should I load it again?

2

There are 2 answers

0
Berťák On

You are right, onCreate is a good place to initialize your variable. Apparently getResources() method cannot be used before activity (context) is properly initialized.

However, if you don't need a super effective code, you can simply use getResources().getStringArray(R.array.types) when you need your array or you can create a method

private String[] getTypes() {
    return getResources().getStringArray(R.array.types);
}
0
Slampy On

The problem is that you're trying to call a Context method when the Activity is not created. Try call it in OnCreate() :)