Eric S. Bullington
Eric S. Bullington

Reputation: 1001

Get list of files in arbitrary subdirectory of Android internal (private) storage

This question has been asked, but no working answer has been proposed. Someone asked and answered a similar question here: How to get list of files from a specific folder in internal storage? Unfortunately, the proposed answer (getAbsoluteDir) in fact returns a new file using the same path as the file provided.

So here it is again: I have the string name used to create a subdirectory (using file.mkdir()) that resides in my app's private internal storage (/data/data/come.my.app/file). How do use that string name to list the files that reside in that subdirectory? The only way I can come up with is to get the subdirectory's File object from the subdirectory name by looping through all the subdirectories in that app directory. Surely there is a more direct way...

The reason why I'm doing this is I'm passing a reference to this directory (because of the files it contains) through a bundle (across Activities). If there's a better way to do that, I'm open to suggestions.

Upvotes: 1

Views: 3246

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

Unfortunately, the proposed answer (getAbsoluteDir) in fact returns a new file using the same path as the file provided.

Well, you could skip the lister line, and use mydir.list() instead. However, the code there does not "return" anything -- list() returns the files in a directory, and in that answer, it shows iteration over that list.

How do use that string name to list the files that reside in that subdirectory?

You can use:

File dir=getDir(whateverYourStringNameIs);

dir.list();

Or:

File dir=new File(getFilesDir(), whateverYourStringNameIs);

dir.list();

Basically, get a File object on your directory (which you already know how to get, as you called mkdir() on one), then call list() to get the contents. Once you have the File object, the rest is standard Java I/O.

The reason why I'm doing this is I'm passing a reference to this directory (because of the files it contains) through a bundle (across Activities).

Assuming that these are all your own activities, you could call getAbsolutePath() on your File to get a String for your Bundle. Then, on the other side, use new File(bundle.getString("whateverYouCalledIt")) to reconstitute the File object. Or, pass in the Bundle a string that represents the relative path within your app's portion of internal storage, and use that with getDir() or getFilesDir() to build a File object pointing to that same path.

Upvotes: 5

Related Questions