如何从arrays.xml文件中获取字符串数组


116

我只是想显示我的数组中的列表arrays.xml。当我尝试在模拟器中运行它时,我收到了强制关闭消息。

如果我在Java文件中定义数组

String[] testArray = new String[] {"one","two","three","etc"};

它有效,但是当我使用

String[] testArray = getResources().getStringArray(R.array.testArray);

它不起作用。

这是我的Java文件:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
 String[] testArray = getResources().getStringArray(R.array.testArray);

 /** Called when the activity is first created. */
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  // Create an ArrayAdapter that will contain all list items
  ArrayAdapter<String> adapter;

  /* Assign the name array to that adapter and 
     also choose a simple layout for the list items */ 
  adapter = new ArrayAdapter<String>(
    this,
    android.R.layout.simple_list_item_1,
    testArray);

  // Assign the adapter to this ListActivity
  setListAdapter(adapter);
 }


}

这是我的arrays.xml档案

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
  <array name="testArray">  
    <item>first</item>  
    <item>second</item>  
    <item>third</item>  
    <item>fourth</item>  
    <item>fifth</item>  
  </array>
</resources>

Answers:


212

您无法以testArray这种方式初始化字段,因为应用程序资源仍未准备好。

只需将代码更改为:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

我还要补充一点,数组名称中不允许使用“-”。Eclipse并没有警告我,xml文件似乎还不错,我花了一段时间才意识到这是引起问题的原因。“ _”工作正常。
Lesik2008 2014年

30

您的array.xml不正确。改成这样

这是array.xml文件

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

无法解决在初始化Activity上下文和资源之前初始化此字段的问题。
Lubos Horacek

2

您的XML并不十分清楚,但是如果您将数字设为数字和/或在其定义中添加空格,则数组XML可能会导致强制关闭。

确保将它们定义为没有前导或尾随空白

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.