InputStream is = getResources().openRawResource(R.raw.babynames);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
reader.readLine();
while ((line = reader.readLine()) != null) {
Log.d("MyActivity", "Line: " + line);
String[] tokens = line.split(",");
BabyName name = new BabyName();
name.setGender(tokens[1]);
name.setMeaning(tokens[2]);
name.setName(tokens[3]);
name.setOrigin(tokens[4]);
babyNames.add(name);
Log.d(TAG, "Just created: " + name);
}
} catch (IOException e) {
Log.wtf("MyActivity", "Error reading data file on line" + line, e);
e.printStackTrace();
}
我正在尝试此操作,但应用程序崩溃了,并且出现了数组索引错误,并且在日志中我正在获取数据
答案 0 :(得分:1)
BabyName name = new BabyName();
name.setGender(tokens[1]);
name.setMeaning(tokens[2]);
name.setName(tokens[3]);
name.setOrigin(tokens[4]);
索引不应该从0开始
name.setGender(tokens[0]);