Search code examples
androidfilepathfilepicker

Getting wrong file path using "registerForActivityResult"


mGetContent =
            registerForActivityResult(new ActivityResultContracts.GetContent(),
                    uri -> {
                        if(uri!=null) {
                            noticeUri = uri;
                            textViewNoticeName.setText(uri.getPath());
                        }
                        else{
                            Toast.makeText(CROption.this, "No file selected", Toast.LENGTH_SHORT).show();
                        }
                    });

Launching picker like this:

mGetContent.launch("application/pdf");

It's working in android 10. But in android 7(emulator), it is showing wrong path like this
Choosing this file
enter image description here

Getting path like below:
Wrong path



I can read file size and can also upload the file in cloud storage. But I can't read the file name , file type and correct path.
haven't taken storage permission.
I want to allow user to select a pdf file for uploading. I need the file name and type for this. I haven't worked in storage before.


Solution

  • Get file name like this:

      Cursor returnCursor =
            getContentResolver().query(uri, null, null, null, null);
      int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
       returnCursor.moveToFirst();
    textViewNoticeName.setText(returnCursor.getString(nameIndex)));
    

    You can get filetype like this:

     String mime=getContentResolver().getType(uri);