我是编写Android应用程序的小伙子,使用getResources().getStringArray()
时遇到问题。
我在一个名为 res.values.strings.xml 的文件中从Eclipse(或手工)创建一个string-array
资源,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="BlueStartCommands">
<item> NO_CMD</item>
<item> LOCK_CMD</item>
<item> UNLOCK_CMD</item>
<item> TRUNK_RELEASE_CMD</item>
<item> PANIC_CMD</item>
<item> REMOTE_START_CMD</item>
<item> REQ_START_MONITOR_CMD</item>
<item> REQ_PASSIVE_LOCK_SETTINGS_CMD</item>
<item> REQ_STOP_MONITOR_CMD</item>
<item> PING_CMD</item>
</string-array>
<string-array name="CMD">
<item>AAAAAA</item>
<item>BBBBBB</item>
</string-array>
</resources>
然后我尝试访问Activity
中的数组。它崩溃了:
public class TestApp2Activity extends Activity {
static boolean firstWrite=true;
TextView DebugWindow;
ViewFlipper flipper;
Button FlipBtn;
Button SwitchBtn;
EditText MessageBox;
Spinner PredefinedMessages;
OnItemSelectedListener PredefinedMessageSelected;
int SelectedPredefinedMessage=0;
String[] MyPredefinedCommands = {"fsd", "fdg", "sdf", "saf", "w", "v", "u", "t", "z", "y", "x"};
String[] cmd = getResources().getStringArray(R.array.CMD);
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
flipper=(ViewFlipper)findViewById(R.id.details);
FlipBtn=(Button)findViewById(R.id.Button01);
SwitchBtn=(Button)findViewById(R.id.Button04);
DebugWindow=(TextView)findViewById(R.id.textView1);
MessageBox=(EditText)findViewById(R.id.editText2);
PredefinedMessages=(Spinner)findViewById(R.id.spinner1);
PredefinedMessages.setPrompt("Please enter a predefined command");
@SuppressWarnings("rawtypes")
ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.BlueStartCommands , android.R.layout.simple_spinner_item);
PredefinedMessages.setAdapter(adapter);
PredefinedMessages.setOnItemSelectedListener(new ListView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> a, View v, int i, long l) {
try {
// Remembers the selected Index
SelectedPredefinedMessage = i;
String s = MyPredefinedCommands[i];
System.out.print(s);
MessageBox.setText(cmd[i]);
}
catch(Exception e) {
System.out.println("Nay, cannot get the selected index");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
但是,当我使用创建的代码array-string
cmd 时,它可以正常工作!
那是为什么?
答案 0 :(得分:3)
我认为问题在于您在调用onCreate()
之前尝试检索数组(您在全局声明中指定它)。
在您现在宣布它的班级中尝试String[] cmd;
,
和onCreate()函数中的cmd = getResources().getStringArray(R.array.CMD);
。
答案 1 :(得分:0)
我已在res / values / arrays.xml中定义了我的数组,并使用以下命令访问它们:
CharSequence[] monthArray = getResources().getStringArray(R.array.Month);
List<CharSequence> monthArrayList = Arrays.asList(monthArray);