0

I want to upload my document to server.

When I get uri path it failed to convert realpath from uri.

my uri path

content://com.android.providers.media.documents/document/document%3A18776

Issue when getting document path from uri in android 11.

```
public static String getPathFromUri(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }   else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
             //   contentUri = MediaStore.Files.FileColumns;
            }else if ("document".equals(type)){

                contentUri =  MediaStore.Files.getContentUri("external",Long.valueOf(split[1]));

             //   return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath() + "/" + split[1];
             //   return  "content://com.android.providers.media.documents/document/"+split[1];

            }

            // only pdf
            String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
            String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
            String[] selectionArgsPdf = new String[]{ mimeType };

            final Uri contentUri1 = ContentUris.withAppendedId(
                    Uri.parse(contentUri.getPath()), Long.valueOf(split[1]));

        //    getDataColumn(context, contentUri1, null, null);

       /*     final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };*/

            return contentUri.toString();//getDataColumn(context, contentUri1, selectionMimeType, selectionArgsPdf);

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

             String id = DocumentsContract.getDocumentId(uri);

            if (id.startsWith("raw:")){

                id = id.replaceFirst("raw.","");
                File file = new File(id);

                if (file.exists()){

                    return  id;
                }

            }

            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), 
        Long.valueOf(id));

          return   getDataColumn(context, contentUri, null, null);
        }// MediaProvider

    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}
```

This code I have tried for getting the realpath from uri in android 11 but it return null. and it is working fine android 10 and below android 10.

Alishan
  • 87
  • 1
  • 8
  • `I want to upload my document to server. ` For that you can use the uri directly. You dont need 'a real path'. For no Android version. – blackapps Aug 17 '21 at 08:14
  • 1
    Don't bother trying to get real path, if your uploader won't work with uri's then you can get a file descriptor or file stream from the content resolver which a lot of java libraries will take instead of a file object. – Andrew Aug 17 '21 at 08:42
  • @blackapps I am using multipart request of retrofit is is possible to pass uri as file? – Alishan Aug 17 '21 at 08:47
  • 1
    Google for inputstreamrequestbody. Your problem has been discussed nearly every week here the last two years on stackoverflow. And solved using an InputStream. – blackapps Aug 17 '21 at 08:49
  • @Andrew I am using multipart request of retrofit InputStream will work in this case? – Alishan Aug 17 '21 at 08:49
  • @blackapps using input stream document is uploading fine no need to get realpath from uri thanks you have saved my time. – Alishan Aug 17 '21 at 09:21
  • @Andrew using input stream document is uploading fine no need to get realpath from uri thanks you have saved my time. – Alishan Aug 17 '21 at 09:21
  • Can you please upload your solution. I am stuck in the same – Amanpreet Kaur Nov 12 '22 at 10:49

1 Answers1

-1

Here is a tested class :

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;

public class FileHelper {

    public Context mContext;

    public FileHelper(Context context)
    {
        this.mContext = context;
    }

    public String getRealPathFromUri(final Uri uri) {
        // DocumentProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(mContext, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(mContext, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(mContext, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(mContext, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    private String getDataColumn(Context context, Uri uri, String selection,
                                 String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public String getMimeType(Uri uri) {
        String mimeType = null;
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            ContentResolver cr = mContext.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                    .toString());
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());
        }
        return mimeType;
    }


    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

And then just use it from every where : ( Replace CONTEXT and URI )

FileHelper fileHelper = new FileHelper(CONTEXT);
String filePath = fileHelper.getRealPathFromUri(URI);