简体   繁体   中英

Java/Android recursive file null pointer exception

I'm trying to recursively get a directory structure in Java, on an Android emulator, with what I think is a fairly straightforward bit of code:

public void list(File file) 
{
    if(file.isDirectory())
    {
       File[] children = file.listFiles();
       for(int i = 0; i < children.length; i++)
       {
           Log.d(TAG, children[i].getName());
           list(children[i]);
       }
    }
}

It works fine (so far) unless I run it in the root of the emulator's SD card, at which point it throws a null pointer exception. LogCat claims it's thrown when the method calls itself, but I have to wrap the entire for loop in a try/catch block in order to catch the exception.

I've tried about half a dozen permutations on the same sort of theme, and the above is the most bland and safe I can come up with, but they all throw this error. I'm either doing something silly, or there's an odd object lurking in the root of the emulator's SD card which reports as a directory but returns a bogus value with .listFiles(). That .android_security certainly looks a bit shifty.

Would anyone be so kind as to tell me which, if either of them, it is?

I'd be more defensive and write it this way:

public void list(File file) 
{
    if (file != null && file.isDirectory())
    {
       File[] children = file.listFiles();
       if (children != null)
       {
           for(int i = 0; i < children.length; i++)
           {
               if (children[i] != null)
               {
                   Log.d(TAG, children[i].getName());
               }
               list(children[i]);
           }
        }
    }
}

Interesting: Is that Log class yours, or is that a logging solution that's commonly used on Android?

You could be getting null pointer exceptions because the SD card is unavailable (maybe because your phone is connected to your pc while debugging?)

I've had a similar error before and that was the reason why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM