javaandroidfileenoent

Android ENOENT with some files


I use a Intent to get pictures path and open them into a File. I can open files allocated in "Camera" folder like "/storage/emulated/0/DCIM/Camera/IMG_20160817_232858.jpg", but I cannot open files in locations like "/storage/emulated/0/Pictures/1634894_.png". Using file.exists() it just says that it doesn't. Need to say that I'm using API 23 and I request READ_EXTERNAL_STORAGE, so this souldn`t be a problem... But I can't access those files even with that. What can be wrong?

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            File file = new File(picturePath);
            if(file.exists()) {

            } else {

            }
            cursor.close();
        }
    }

Updated: it doesn't happens with all the files from the same folder, just some of them, but they really exist since I can open them from the gallery.

Update2: I use this Intent.

Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

Update3: Running time permissions:

if (Build.VERSION.SDK_INT >= 23) {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED) {
                    SomeWork();
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
            }
            else { 
                SomeWork();
            }

Permissions in Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Solution

  • The MediaStore will index images that are not accessible to you from the filesystem. There is no requirement for a DATA column to return a value that you can use.

    Instead, stop trying to get a File, and use the Uri itself: