Search code examples
androidurlandroid-contentprovider

How to handle content:// Uri in order to open a file


I'm using the Android's DownloadManager class. It returns Uri with content:// scheme after clicking on the "downloaded file" notification. I have a method which is now only able to open files using file Uris (with "file" scheme). What is the easiest way to get the File file from the content Uri. Any examples are welcome.

public PlsReader(URI path) {

   File file = new File(path);
}

Solution

  • try this 1st method to get is below

    Uri.getPath();
    

    this will give u whole absolute path of any file

    and 2nd method is below

      Strinf absolutepath =   getRealPathFromURI(this,URI);
    

    and method getRealPathFromURI is here

      public String getRealPathFromURI(Context context, Uri contentUri) {
          Cursor cursor = null;
          try { 
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, 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();
            }
          }
        }
    

    then pass this absolutepath string to your file like this

    public PlsReader(String absolutepath ) {
    
       File file = new File(absolutepath );
    }
    

    best of luck dude :)