Android file chooser
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Bear
Updated on July 23, 2022Comments
-
Bear almost 2 years
I want to make a file uploader. And I hence I need a file chooser but I don't want to write this by myself. I find OI file manager and I think it suits me. But how can I force user to install OI file manager? If I cannot , is there a better way to include a file manager in my app? Thx
-
Kurtis Nusbaum over 12 yearsI'd even go so far as to also direct them to app on the market.
-
Bear over 12 yearsThx, but I get the content uri ---content://org.openintents.cmfilemanager/mimetype//mnt/sdcard/1318638826728.jpg instead of file path. Could I convert it into file path?
-
Paul Burke over 12 yearsUpdated answer to show how to get the file path, as well as creating a File instance that gives you convenience callbacks like file.getName() and file.getAbsolutePath().
-
Bear over 12 yearsBut I can't find FileUtils....
-
Paul Burke over 12 yearsSorry, I forgot to include my FileUtils.getPath() at first.
-
Zala Janaksinh almost 12 yearswithout use file explorer it`s possible?can we make to display file structure in android?
-
Benoit Duffez over 11 yearsOn Google Code the license was explicitly Apache 2.0, is it still the case on GitHub? Thanks.
-
Paul Burke over 11 years@Bicou Thanks for the note. Your nudge helped me to stop being lazy and make some minor changes. :-) I just pushed an update to the library that includes the license.
-
Dheeraj Bhaskar about 11 yearsjava.lang.NoClassDefFoundError com.ipaulpro.afilechooser.utils.FileUtils . What might I be doing wrong?
-
Richard Walters almost 11 yearsThanks for this, especially the
getPath()
code! I found on one device for mecursor.getString(column_index)
returns afile:///
URL, and I had to run it through a second pass to extract the actual path name. -
vilpe89 almost 11 years@Bear You just need to copy that getPath method to your own class and that's it!
-
David Doria over 10 yearsDo I have to use intents even if I don't need 3rd party components? Can this be used like a DialogFragment?
-
Paul Burke over 10 years@DavidDoria Sure, you can also simply call
startActivity(Context, FileChooserActivity.class)
and set the theme you want in the Manifest. Listen for theUri
inonActivityResult
just as you would normally. -
David Doria over 10 years@PaulBurke Sorry, I'm very new to this. I don't see a startActivity function here developer.android.com/reference/android/app/… that takes anything but an intent? The closest I found online was startActivity(new Intent(MainActivity.this, FileChooserActivity.class)); - is that the best way?
-
Paul Burke over 10 years@DavidDoria My apologies! I did mean
startActivity(Intent)
. -
Phantômaxx about 10 yearsSo, one of the requirements for your app users is... install AndExplorer?!
-
Chandan Reddy about 9 yearshow can I enable multi select ..?
-
keshav kowshik almost 9 years@PaulBurke: I am using your method to attach a file and upload it to server. But I am facing an error, can you please help me. Please see this question: stackoverflow.com/questions/30882833/…. Thanks in advance.
-
wangqi060934 over 8 yearsThis answer does not consider the uri like this:"content://com.android.providers.media.documents/document/image:62".
-
Mehul Joisar almost 8 years@wangqi060934: how did you manage to work with such uri? please share your experience to achieve the functionality
-
wangqi060934 almost 8 years@MehulJoisar,the library " aFileChooser" is perfect now.
-
Angad Singh over 7 yearsOr you can use this one: github.com/Angads25/android-filepicker
-
Code_Worm over 7 yearsthanks a million aFileExplorer is amazing
-
salih kallai over 6 yearsSir, how to filter a specific file type like pdf, doc ect...
-
Mohamed Atef over 6 yearsHere you can find all cases to select file from document and all types of mobiles github.com/memo1231014/MUT-master/blob/master/MUT/src/com/…
-
JFreeman over 6 years@PaulBurke - Thank you very much i used you android studio project and it worked great. The only problem i had is that when the
onActivityResult
function was called theREQUEST_CHOOSER
did not trigger the correct action - found in your git-hub project, in your README.markdown file under usage in yourswitch
. (i changed it toREQUEST_CODE
) -
Mr. Sajid Shaikh almost 6 yearsis this lib provide multiple file selection ?
-
learner almost 5 yearsHere path getiing null some time,i can see in log "coloumn name _data not able to find" message.
-
Jomme about 4 yearsToday, there are a lot of deprecated classes/methods in the module like 'AsyncTaskLoader'. Needs some updates.
-
Ahmad about 4 yearsHi i have an issue in onActivityResult when i didn't select any file and press back it doesn't open again can any one help ?