0

I'm trying to load directories located in a path into a ListView. Whenever I ask it to list directories located at the root "/" it works. However, when I try to ask it to load file within another directory, such as Environment.getExternalStorageDirectory().toString(), it crashes on load and says the following:

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

It says it's crashing at my ArrayAdapter. I think (know?) it's because I'm treating File[] like it's a String[]. However, I can't figure out how to fix that.

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);
    }

If I try:

        String[] backuplist = f.listFiles();

Android Studio just tells me to change it to File[].


Solved

To fix it, I had to create another array, ArrayList<String> backupslist = new ArrayList<String>(); , then add a for File loop that added directories to the array:

for (File inFile : dirlocation) {
            if (inFile.isDirectory()) {
                backupslist.add(inFile.getName());
            }
        }
Community
  • 1
  • 1
epiquiem
  • 3
  • 2
  • Please post the entire stack trace, not just a couple of lines. Also indicate what lines in that stack trace refer to lines in your source code snippets above. Bear in mind that `listFiles()` can return `null`, and you are not handling that case. – CommonsWare Apr 05 '15 at 20:54

1 Answers1

0

As stated in java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: storage == null this exception is raised when when the array parameter passed to ArrayAdapter(Context, int, T[]) is null. . So backuplist should be null in your sample.

Community
  • 1
  • 1
GioLaq
  • 2,489
  • 21
  • 26