我需要从 res/raw/file.txt 下的 txt 文件中读取数据,并在 ListView 中显示每一行。但是当应用程序启动时 ListView 是空的。这是在 onCreate 之前定义的:
private SimpleAdapter sa;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
这是代码:
InputStream inputStream = getResources().openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try
{
HashMap<String, String> item;
while ((line = reader.readLine()) != null)
{
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
{
item = new HashMap<String, String>();
item.put("line1", strings[0].trim());
item.put("line2", strings[1].trim());
list.add(item);
}
}
mTextView.setText("");
sa = new SimpleAdapter(this, list,
R.layout.result,
new String[] { "line1","line2" },
new int[] {R.id.word, R.id.definition});
mListView.setAdapter(sa);
reader.close();
}
catch(Exception e)
{
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}