-1
Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

cursor.getString(columnIndex) Returns Null Where as the selectedImage is not null.

Any suggestion on how I can create file from URI?

2 Answers2

0

Cursor returns null when getting filepath from URI

A Uri is not a file. A Uri does not have to point to a file, let alone a file on the filesystem that you can access.

Any suggestion on how I can create file from URI?

Use ContentResolver and openInputStream() to get an InputStream on the content identified the Uri. Ideally, just use that InputStream directly. If, for some reason, you truly need a file:

  • Create a FileOutputStream on some file that you control (e.g., in getCacheDir())

  • Copy the bytes from the InputStream to the FileOutputStream

  • Use the file that you just created, deleting it when you are done

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
-3

Use this method to get path:

public String getPath(Uri uri) {
    // just some safety built in
    if (uri == null) {
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}

And in onACtivityResult use this:

Uri selectedImage = data.getData();
Pang
  • 9,564
  • 146
  • 81
  • 122
Preet
  • 13
  • 4