Erich García
Erich García

Reputation: 1874

Search specific file in external storage

I'm developing an APP, and it uses the Read External memory to read an .db file.

Currently I have a Shared Preferences which can be modified to point to the location of that file in external storage.

I have the steps:

  1. When the app launch in first time, locate the file based in Shared Preferences setting.
  2. If the file not found, search for it in background.
  3. If found it, update the location in shared preferences and continue loading the app.
  4. If not found it just load a view with a sad face.

My question: How do I accomplish step 2 (search for a file named my-file.db in external storage)? so I may perform step 3

Edited: Added the actual working method, but now it don't return the location.

//Try to search the DB:

...
            String path = Environment.getExternalStorageDirectory().toString() + "/";
            Files fileLocation = new Files();
            String location = fileLocation.searchDB(path);
            Log.e("elBacheAPP DATA", "FileName:" + location);

            //No DatabaSe was Found!!!
            setContentView(R.layout.no_database);
            toolbarTitle = "No hay Datos";
...

public String searchDB(String path) {

        File directory = new File(path);
        File[] files = directory.listFiles();

        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                //Found it!
                if (files[i].getName().equals("elbacheapp.db")) {
                    Log.e("elBacheAPP DB Found", "FileName:" + files[i].getAbsolutePath());
                    String location = new String(files[i].getAbsolutePath());
                    return location;
                }
                searchDB(path + files[i].getName());
            }
        }
        return "";
    }

This is the output:

12-26 22:13:41.829 7420-7420/com.bachecubano.elbache E/elBacheAPP DB Found!: FileName:/storage/emulated/0/testing/elbacheapp.db
12-26 22:13:41.829 7420-7420/com.bachecubano.elbache E/elBacheAPP: Location:/storage/emulated/0/testing/elbacheapp.db
12-26 22:13:41.832 7420-7420/com.bachecubano.elbache E/elBacheAPP DATA: FileName:

Upvotes: 0

Views: 91

Answers (1)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

My first questions would be,

  1. Why are you storing your DB in external storage, as opposed to your app's internal (private) storage?
  2. Why don't you know the path of your DB?

What being said, you can use File.list() recursively starting from Environment.getExternalStorageDirectory() to locate the file of interest. I'll leave the details of that up to you, but it's going to go something like,

find(File f) {
  if (f is a file) {
    if (f is the file of interest) { 
      yes: do the work
    }
  else if (f is a dir) {
    for (f2 in f) { find(f2); }
  }
}

Upvotes: 1

Related Questions