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 i
I'm using something like this:
String scheme = uri.getScheme();
if (scheme.equals("file")) {
fileName = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
String[] proj = { MediaStore.Images.Media.TITLE };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
cursor.moveToFirst();
fileName = cursor.getString(columnIndex);
}
if (cursor != null) {
cursor.close();
}
}
String Fpath = getPath(this, uri) ;
File file = new File(Fpath);
String filename = file.getName();
developer.android.com has nice example code for this: https://developer.android.com/guide/topics/providers/document-provider.html
A condensed version to just extract the file name (assuming "this" is an Activity):
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
For Kotlin, You can use something like this :
object FileUtils {
fun Context.getFileName(uri: Uri): String?
= when (uri.scheme) {
ContentResolver.SCHEME_FILE -> File(uri.path).name
ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
else -> null
}
private fun Context.getCursorContent(uri: Uri): String?
= try {
contentResolver.query(uri, null, null, null, null)?.let { cursor ->
cursor.run {
if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
else null
}.also { cursor.close() }
}
} catch (e : Exception) { null }
Please try this :
private String displayName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}