Android: Pass string array from values to .java

2019-07-29 09:05发布

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?

2条回答
甜甜的少女心
2楼-- · 2019-07-29 09:11

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(...);
查看更多
女痞
3楼-- · 2019-07-29 09:23

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
    }
}
查看更多
登录 后发表回答