Android: invalid file name for selected file (from select file)

I have a screen where, when I click a button, I open a selection file, and then I select a file called "Test.jpg" for further work. I use the following code to get the name of this file.

Uri uri = data.getData(); File file = new File(uri.getPath()); String fileName = file.getName(); 

Here are the debugger results

 file.getName() => 167522 file.toString() => /external/images/media/167522 

I want to get Test.jpg as my file name. Please let me know what is wrong with my code.

+5
source share
3 answers

Need a path from your uri. there is a way to get the 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; } 

Get file name

 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()+""); } 

Output

 uri: content://com.android.providers.media.documents/document/image%3A12876 FileName : profile.png 
+4
source

Try using 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(); } } } 
0
source

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 } 
0
source

Source: https://habr.com/ru/post/1269751/


All Articles