I am using 3rd party file manager to pick a file (PDF in my case) from the file system.
This is how I launch the activity:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(getString(R.string.app_pdf_mime_type));
intent.addCategory(Intent.CATEGORY_OPENABLE);
String chooserName = getString(R.string.Browse);
Intent chooser = Intent.createChooser(intent, chooserName);
startActivityForResult(chooser, ActivityRequests.BROWSE);
This is what I have in onActivityResult
:
Uri uri = data.getData();
if (uri != null) {
if (uri.toString().startsWith("file:")) {
fileName = uri.getPath();
} else { // uri.startsWith("content:")
Cursor c = getContentResolver().query(uri, null, null, null, null);
if (c != null && c.moveToFirst()) {
int id = c.getColumnIndex(Images.Media.DATA);
if (id != -1) {
fileName = c.getString(id);
}
}
}
}
Code snippet is borrowed from Open Intents File Manager instructions available here:
http://www.openintents.org/en/node/829
The purpose of if-else
is backwards compatibility. I wonder if this is a best way to get the file name as I have found that other file managers return all kind of things.
For example, Documents ToGo return something like the following:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fsdcard%2Fdropbox%2FTransfer%2Fconsent.pdf
on which getContentResolver().query()
returns null
.
To make things more interesting, unnamed file manager (I got this URI from client log) returned something like:
/./sdcard/downloads/.bin
Is there a preferred way of extracting the file name from URI or one should resort to string parsing?