Search code examples
androidandroid-contentresolverandroid-storage

Android storage access framework returning "raw" path


Trying to use the Storage access framework to select a file from the device (an html file that I wan't to parse) but it returns a file path that doesn't appear to be a content URI (/document/raw:/storage/emulated/0/Download/test.html) and that errors when I use it with the content resolver.

Intent to fetch file:

boolean alreadyHasReadPermissions = hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE);    
if (alreadyHasReadPermissions) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("text/html");
    try {
        activity.startActivityForResult(intent, fileChooserResultCode);
    }catch(ActivityNotFoundException e){
        Toast.makeText(activity, R.string.unable_to_open_file_picker, Toast.LENGTH_LONG).show();
    }
}

Code to read a file:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==fileChooserResultCode){
        if(resultCode == Activity.RESULT_OK && data.getData()!=null) {
            String contentUriString = data.getData().getPath();
            try {
                Uri contentUri = Uri.parse(contentUriString);
                InputStream inputStream = getContentResolver().openInputStream(contentUri); // <<< Errors with FileNotFoundException
                BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
                ...
            }catch (NullPointerException | IOException e){
                Toast.makeText(this, R.string.unable_to_open_file, Toast.LENGTH_LONG).show();
            }
        }
    }
}

Solution

  • Delete:

    String contentUriString = data.getData().getPath();
    

    and delete:

    Uri contentUri = Uri.parse(contentUriString);
    

    And change:

    InputStream inputStream = getContentResolver().openInputStream(contentUri);
    

    to:

    InputStream inputStream = getContentResolver().openInputStream(data.getData());
    

    IOW, do not call getPath() on a Uri.