I am launching the intent for selecting documnets using following code.
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"), 1);
} 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();
}
}
In onActivity results when i am trying to get the file path it is giving some other number in the place of file name.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
File myFile = new File(uri.toString());
String path = myFile.getAbsolutePath();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
That path value i am getting like this. "content://com.android.providers.downloads.documents/document/1433" But i want real file name like doc1.pdf etc.. How to get it?
When you get a content:// uri, you'll need to query a content resolver and then grab the display name.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}