-1

I have found a piece of code for Android(Java) which searches sd-card for a given file name(string) in case that the file exists in sd-card it works fine but if there's no file with that name it will throw null pointer exception. Can anyone help me please? or give me another alternative? here's the code:

public File findFile(File dir, String name) {
    File[] children = dir.listFiles();

    for(File child : children) {//the exception is thrown here!
        if(child.isDirectory()) {
           File found = findFile(child, name);
           if(found != null) return found;
        } else {
            if(name.equals(child.getName())) return child;
        }
    }

    return null;
}

Here's the logcat results:

threadid=1: thread exiting with uncaught exception (group=0x400205a0)
FATAL EXCEPTION: main
java.lang.NullPointerException
at ir.zinutech.ssn.Settings.findFile(Settings.java:93)//>> which is "for(File child : children) { "
at ir.zinutech.ssn.Settings.findFile(Settings.java:95)//>> which is "File found = findFile(child, name);//the exception is thrown here!"
at ir.zinutech.ssn.Settings.onClick(Settings.java:69)
at android.view.View.performClick(View.java:2532)
at android.view.View$PerformClick.run(View.java:9293)`end`
Erfan
  • 163
  • 1
  • 8
  • 2
    post stacktrace. the exception cannot be thrown at the line you indicate, because there is no call on a null object made. (the only call is made on `this`, which is not null by definition) – njzk2 May 12 '14 at 14:41
  • the actual error is in `for(File child : children) {`, meaning the null is `children`, meaning `dir` is not a directory, which is quite unlikely. – njzk2 May 12 '14 at 16:11
  • @njzk2 so how should I solve it? any ideas? – Erfan May 12 '14 at 16:12
  • again, you exception does not match the code. the lines 93 and 94 should be one after the other, but in your code there is `if(child.isDirectory()) {` is between, suggesting that you are not actually testing `isDirectory`, which does explain the crash. Please post consistent code and stacktrace. – njzk2 May 12 '14 at 16:16
  • I changed the code, the places are right and I will fix line numbers now – Erfan May 12 '14 at 16:17

2 Answers2

1

I think you can modify the code a little. Because not all of recursion case return a value/object.

package vinhnt.example;

import java.io.File;

public class Finder {
    public static void main(String... args) {
        File result = findFileInDirectory(new File("C:/"), "Finder.class");
        if (result == null) {
            System.out.println("File not found");
        }else {
            System.out.println(result.getAbsolutePath());
        }

    }
    public static File findFileInDirectory(File dir, String name) {
        File[] children = dir.listFiles();
        if (children==null) return null;

        for(File child : children) {
            if(child.isDirectory()) {
               File result = findFileInDirectory(child, name);
               if (result!=null) return result;
            } else {
                String fileName = child.getName();
                if(name.equals(fileName)) {
                    System.out.println(fileName);
                    return child;
                }
            }
        }
        return null;
    }
}
VinhNT
  • 1,091
  • 8
  • 13
  • This code solved the problem when there's no file but also it won't find the file when there's one... – Erfan May 12 '14 at 15:57
  • 1
    this does not work if the file is not in the first directory, as it cannot test the second directory. – njzk2 May 12 '14 at 16:09
  • 1
    Well, I tried your original code in windows, and I got the NullPointerException. Then, I tried debugging, and see the NullPointerException will appear when the program attempt to list the file of a folder that programm do not have permission, the File[] children = dir.listFiles(); return null and make the next for loop raise exception So, let me update the answer, my program should return the first found file – VinhNT May 12 '14 at 16:45
  • `new File("C:/")` ? did you see the `android` tag? – njzk2 May 12 '14 at 20:56
0

Thanks to @njzk2 and @VinhNT helping me i figured out how to solve it, the problem was just as @VinhNT said, some folders couldn't be reached so I modified code so that it won't get trapped in such casses, here's how I handeled it:

File sourceFile = findFile(Environment.getExternalStorageDirectory(),"x.apk");
            if (sourceFile==null){
                Toast.makeText(getApplicationContext(), 
                        "Couldn't find x.apk file in your SD card",
                        Toast.LENGTH_LONG).show();
                break;
            }

and in search function :

public File findFile(File dir, String name) {
    File[] children = dir.listFiles();
    try{
        for(File child : children) {
            if(child.isDirectory()) {
               File found = findFile(child, name);
               if(found != null) return found;
            } else {
                if(name.equals(child.getName())) return child;
            }
        }
    }catch(Exception e){
        //ignore here because we have no access to this folder
        return null;
    }

    return null;
}

hope it helps other people who get stuck like me.

Erfan
  • 163
  • 1
  • 8
  • Ha, I have no android sdk version for my current pc, i think just change the path to adapt app for apk, tell me if i am wrong – VinhNT May 13 '14 at 07:54
  • Actually I want to share my app using a button inside app itself, so I'm not sure that where is the folder that user has downloaded app into it(downloads, icm/bazaar and etc) so due to variation of folders I need to make my search go through all of sdcard and I can't just focus on a single folder in sdcard. – Erfan May 13 '14 at 08:10
  • I see this one http://stackoverflow.com/questions/7908193/how-to-access-downloads-folder-in-android I do not think you have to search all sd card for finding your apk file, just find in download folder is good enough – VinhNT May 13 '14 at 08:45
  • Nah, the users may just get app from anywhere(maybe download in pc and then copy to sd-card) so I need to check it all – Erfan May 13 '14 at 09:13
  • 1
    a version without recursion https://sites.google.com/site/nguyenthevinhbk/home/file-finder – VinhNT May 13 '14 at 09:28