我试图将位于路径中的目录加载到ListView中。每当我要求它列出位于根目录的目录时,#34; /"有用。但是,当我试图要求它在另一个目录中加载文件时,例如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());
}
}
答案 0 :(得分:0)
如java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: storage == null中所述,当传递给ArrayAdapter(Context,int,T [])的数组参数为空时,会引发此异常。。
因此,backuplist
应为null
样本。