Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PDF (not image) file path from uri android [duplicate]

I am launching the intent for selecting documnets using following code.

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"), 1);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

In onActivity results when i am trying to get the file path it is giving some other number in the place of file name.

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            File myFile = new File(uri.toString());
            String path = myFile.getAbsolutePath();
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

That path value i am getting like this. "content://com.android.providers.downloads.documents/document/1433" But i want real file name like doc1.pdf etc.. How to get it?

like image 853
AndroidDev Avatar asked Jun 20 '14 08:06

AndroidDev


3 Answers

When you get a content:// uri, you'll need to query a content resolver and then grab the display name.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
            String displayName = null;

            if (uriString.startsWith("content://")) {                   
                Cursor cursor = null;
                try {                           
                    cursor = getActivity().getContentResolver().query(uri, null, null, null, null);                         
                    if (cursor != null && cursor.moveToFirst()) {                               
                        displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {           
                displayName = myFile.getName();
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
like image 111
cinthiaro Avatar answered Nov 12 '22 10:11

cinthiaro


First Check if the permission is granted for Application.. Below method is used to check run-time permission'

 public void onClick(View v) {
            //Checks if the permission is Enabled or not...
            if (ContextCompat.checkSelfPermission(thisActivity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSION);
            } else {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, USER_IMG_REQUEST);
            }
        }

and below method is used to find the uri path name of the file

private String getRealPathFromUri(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    CursorLoader cursorLoader = new CursorLoader(thisActivity, uri, projection, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();
    int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column);
    cursor.close();
    return result;
}

and the above method can be used as

 if (requestCode == USER_IMG_REQUEST && resultCode == RESULT_OK && data != null) {
        Uri path = data.getData();
        try {
            String imagePath = getRealPathFromUri(path);
            File file = new File(imagePath);
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part imageFile = MultipartBody.Part.createFormData("userImage", file.getName(), reqFile);
like image 36
Rohan Shukla Avatar answered Nov 12 '22 11:11

Rohan Shukla


Here is the complete solution:

Pass your context and URI object from onActivityResult to below function to get the correct path:

it gives the path as /storage/emulated/0/APMC Mahuva/Report20-11-2017.pdf (where I've selected this Report20-11-2017.pdf file)

String getFilePath(Context cntx, Uri uri) {
    Cursor cursor = null;
    try {
        String[] arr = { MediaStore.Images.Media.DATA };
        cursor = cntx.getContentResolver().query(uri,  arr, 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();
        }
    }
}
like image 43
Jay Patel Avatar answered Nov 12 '22 12:11

Jay Patel