使用Resources.getSystem()

时间:2015-12-23 11:54:18

标签: java android arrays xml

我正在尝试将字符串数组从strings.xml转换为Java类中的数组  (MVC的模型部分),因为我无法使用getResources().getStringArray(R.array.array_name);  (它仅适用于Android组件,如活动,片段等)。

所以我只能使用Resources.getSystem().getStringArray(R.array.array_name); 但是当我尝试在模拟器中运行它时,我得到一个例外。 我发现类似的问题引用了这个问题here。但我不明白解决方案。 这是我的例外:

  

java.lang.RuntimeException:无法启动活动ComponentInfo {com.danirg10000gmail.therpiststep1 / com.danirg10000gmail.therpiststep1.MainActivity}:android.content.res.Resources $ NotFoundException:String array resource ID#0x7f0b0000

(我的例外与上面的链接相同。)

在我的代码中,我有两个类,一个类代表问题,另一个类有一个问题对象列表。 这是我的代码:

public class QuestionM {
private String mQuestion;
private String mAnswer;
private String mExplanation;

 //constructor
 public QuestionM(String question,String explanation) {
    mQuestion = question;
    mExplanation = explanation;
}

public class QuestionnaireM {
private List<QuestionM> mQuestionsList;

//constructor
public QuestionnaireM(){
    mQuestionsList = new ArrayList<>();
    Resources resources = Resources.getSystem();
//when i creating object of that class android points the crush here
    String [] questions = resources.getStringArray(R.array.test);
    String [] questionExplanations = resources.getStringArray(R.array.test_a);
    for (int i=0; i<questions.length; i++){
        QuestionM question = new QuestionM(questions[i],questionExplanations[i]);
        mQuestionsList.add(question);
    }

}

我也不太了解系统级资源和应用程序级资源之间的区别,我在androidDevelopers和Google中搜索它但没有找到任何好的解释。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:1)

根据docs getSystem()执行此操作:

  

返回仅提供访问权限的全局共享Resources对象   系统资源(没有应用程序资源),并且未配置   当前屏幕(不能使用尺寸单位,不改变基础   在方向等)。

因此,使用资源ID getStringArray()调用R.array.test完全没用,因为引用的id是Application resource的。

如果您要加载R.array.test的内容,请使用getStringArray()中的getResources()

您可以将Resources类型的参数传递给构造函数或String[]。即:

public QuestionnaireM(Resources resource) { 
   // stuffs
}

答案 1 :(得分:1)

一个建议,不确定它是否有效。但你可以尝试让我知道。为什么不在QuestionM构造函数中获取上下文并使用接收的上下文初始化类级上下文变量。现在使用此上下文

mContext.getResources().getStringArray(R.array.array_name);

public class QuestionM {

    private String mQuestion;
    private String mAnswer;
    private String mExplanation;
    private Context mContext;

    //constructor
    public QuestionM(String question,String explanation, Context context) {
        mQuestion = question;
        mExplanation = explanation;
        mContext = context;
    }

public class QuestionnaireM {

    private List<QuestionM> mQuestionsList;

    //constructor
    public QuestionnaireM(){
        mQuestionsList = new ArrayList<>();


    //when i creating object of that class android points the crush here
    String [] questions = mContext.getResources().getStringArray(R.array.test);
    String [] questionExplanations = mContext.getResources().getStringArray(R.array.test_a);
    for (int i=0; i<questions.length; i++){
        QuestionM question = new QuestionM(questions[i],questionExplanations[i]);
        mQuestionsList.add(question);
    }

}