Reputation: 986
I have a screen where on a button click I open a file chooser and then I select a file named "Test.jpg" for further operation. I use following code to get name of that file.
Uri uri = data.getData();
File file = new File(uri.getPath());
String fileName = file.getName();
Here are the results from debugger
file.getName() => 167522
file.toString() => /external/images/media/167522
I want to get Test.jpg as my filename. Please let me know what is wrong with my code.
Upvotes: 5
Views: 2747
Reputation: 16032
This method worked for me in Kotlin:
private fun getFilename(uri: Uri): String? {
val cursor = activity?.contentResolver?.query(uri, null, null, null, null)
var filename: String? = null
cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME)?.let { nameIndex ->
cursor.moveToFirst()
filename = cursor.getString(nameIndex)
cursor.close()
}
return filename
}
Upvotes: 3
Reputation: 497
Try to use this method:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Upvotes: 0
Reputation:
Need path from your uri. here is a method to get path from uri.
public 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;
}
try{
//call the getPath uri with context and uri
//To get path from uri
String path = getPath(this, uri);
File file = new File(path);
String filename = file.getName();
Log.e(TAG, "File Name: " + filename);
}catch(Exception e){
e("Err", e.toString()+"");
}
uri: content://com.android.providers.media.documents/document/image%3A12876
FileName : profile.png
Upvotes: 4