我在stack上看到过类似的问题,但都没能找到我人生道路上特殊坎坷的答案。我会捐赠给任何能给我解决方案的人。
我正在尝试显示没有扩展名的外部存储目录中的内容(. txt文件)。我已经导入了(apache.commons.io)。
ArrayAdapter mArrayAdapter;
ListView listView;
String fileNames[];
ArrayList<String> nameArray;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.setContentView(R.layout.activity_read_note_menu);
listView = (ListView) this.findViewById(R.id.readListView);
fileNames = new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/Notes").list();
nameArray = new ArrayList<>();
for (String name: fileNames){
name = name.substring(0, name.indexOf("."));
nameArray.add(name);
Log.d("Files", "FileName:" + name);
}
mArrayAdapter = new ArrayAdapter<>(this, R.layout.list_item_1, nameArray);
mArrayAdapter.sort(new Comparator<String>() {
public int compare(String li1, String li2) {
return li1.compareTo(li2);
}
});
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
String string = (String) listView.getItemAtPosition(i);
Intent intent = new Intent(ReadNoteMenu.this, ReadNote.class);
intent.putExtra(EXTRA_MESSAGE, string);
ReadNoteMenu.this.startActivity(intent);
finish();
}
});
确保从以下代码中获取所有文件列表:
String fileNames[] = new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/Notes").list();
获取所有文件列表后,从文件名中删除扩展名并将该名称存储在数组中。
ArrayList<String> nameArray = new ArrayList<String>();
for (String name: fileNames){
name = name.substring(0, name.indexOf("."));
nameArray.add(name);
Log.d("Files", "FileName:" + name);
}
请在您的适配器中传递nameArray
以完成工作,如下所示:
mArrayAdapter = new ArrayAdapter(this, R.layout.list_item_1, nameArray);