Search code examples
javaandroidfilefilechooser

Android: Incorrect File name for selected file(From file chooser)


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.


Solution

  • 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;
    }
    

    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