farindk
farindk

Reputation: 260

ContentResolver openInputStream() throws FileNotFound on existing file

I have this apparently simple code

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File testfile = new File(path,"image.jpg");

Log.d(TAG,"testfile: " + testfile + " exists: " + testfile.exists());

Uri uri = Uri.fromFile(testfile);
ContentResolver cr = context.getContentResolver();
InputStream istr = cr.openInputStream(uri);

The output is:

testfile: /storage/emulated/0/Pictures/image.jpg exists: true

The uri value is file:///storage/emulated/0/Pictures/image.jpg. Looks like the same file, but the openInputStream() throws an FileNotFoundException.

Any idea why? This is on Android 6.0.1.

Upvotes: 1

Views: 5626

Answers (1)

Clark Wilson
Clark Wilson

Reputation: 389

Add this permission to your AndroidManifest.xml

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

When targetSdkVersion is 23 or above (Android 6), putting this in the AndroidManifest.xml is not enough and you have to request the permission at runtime.

Upvotes: 1

Related Questions