【发布时间】:2015-04-05 20:52:03
【问题描述】:
我正在尝试将位于路径中的目录加载到 ListView 中。每当我要求它列出位于根“/”的目录时,它都会起作用。但是,当我尝试要求它在另一个目录中加载文件时,例如 Environment.getExternalStorageDirectory().toString(),它在加载时崩溃并显示以下内容:
com.hapticlabs.backups I/Info: Path to backups is /storage/emulated/0
com.hapticlabs.backups D/AndroidRuntime﹕ Shutting down VM
com.hapticlabs.backups E/AndroidRuntime﹕ FATAL EXCEPTION:
Process: com.hapticlabs.test, PID: 9155
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hapticlabs.test/com.hapticlabs.test.MainActivity}: java.lang.NullPointerException: storage == null
它说它在我的 ArrayAdapter 上崩溃了。我认为(知道吗?)这是因为我将 File[] 视为 String[]。但是,我不知道如何解决这个问题。
private void getBackups() {
String backupspath = Environment.getExternalStorageDirectory().toString();
Log.i(info, "Path to backups is "+backupspath);
File f = new File(backupspath);
File[] backuplist = f.listFiles();
//String[] testlist = getResources().getStringArray(R.array.test_array);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_item, backuplist);
backupsListView.setAdapter(arrayAdapter);
}
如果我尝试:
String[] backuplist = f.listFiles();
Android Studio 只是告诉我将其更改为 File[]。
已解决
要修复它,我必须创建另一个数组,
ArrayList<String> backupslist = new ArrayList<String>(); ,然后添加一个 for File 循环,将目录添加到数组中:
for (File inFile : dirlocation) {
if (inFile.isDirectory()) {
backupslist.add(inFile.getName());
}
}
【问题讨论】:
-
请发布整个堆栈跟踪,而不仅仅是几行。还要指出该堆栈跟踪中的哪些行引用了上面源代码 sn-ps 中的行。请记住,
listFiles()可以返回null,而您没有处理这种情况。
标签: java android arrays file-io