【问题标题】:App crashing when loading directories into an array using File使用 File 将目录加载到数组中时应用程序崩溃
【发布时间】: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


【解决方案1】:

java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: storage == null 中所述,当传递给 ArrayAdapter(Context, int, T[]) 的数组参数为 null 时会引发此异常。。 所以backuplist 在您的示例中应该是null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2019-09-25
    • 2018-08-26
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多