Android: Pass string array from values to .java

核能气质少年 提交于 2019-12-24 18:05:09

问题


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:


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
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/11111221/android-pass-string-array-from-values-to-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!