8

I am new to working with images in android. I want to load image from internal storage but it is giving me permission denied error then i have added the permission to android manifest file. But still I am not able to complete my task.

Here is my code:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView image = (ImageView)findViewById(R.id.imageView);
        Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
        image.setImageBitmap(bm);

    }
}

logcat:

01-16 15:16:11.345 6533-6533/com.example.jaytanna.imagemap E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg: open failed: EACCES (Permission denied)

It is not displaying any image. Kindly help me with this.Thank you.

Jay
  • 1,055
  • 2
  • 8
  • 17

4 Answers4

16

Check this

     File imgFile = new  File("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
      if(imgFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

        myImage.setImageBitmap(myBitmap);

      };

And include this permission in the manifest file:

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

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

And to handle the response, you can use this code that I copied from http://web.archive.org/web/20160111030837/http://developer.android.com/training/permissions/requesting.html

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • My File is in internal storage. – Jay Jan 16 '17 at 09:53
  • Change file path to your internal storage and run code, if any errors let me know ,and show android studio error logs –  Jan 16 '17 at 09:56
  • 01-16 15:46:51.260 20918-20918/com.example.jaytanna.imagemap E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg: open failed: EACCES (Permission denied) – Jay Jan 16 '17 at 10:17
  • It works, but for some reason the image rotate 90 degrees by itself. Any clue what's wrong? – Hiraeths Oct 07 '20 at 03:04
2

you need to add runtime permisssion check like this:

    public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

use it like:

if(isStoragePermissionGranted()){
 Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
 image.setImageBitmap(bm);

 }

Catch the result in

    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
        Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
       image.setImageBitmap(bm);
    }
}
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • 1
    copy the first and last code snippet outside your `onCreate` in activity – rafsanahmad007 Jan 16 '17 at 10:02
  • 1
    add the middle snippet replacing this code in your `oncreate()` `{ Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg"); image.setImageBitmap(bm);}` – rafsanahmad007 Jan 16 '17 at 10:04
  • Thanks @rafsanahmad007 for this helpful answer. It solved my problem here: https://stackoverflow.com/questions/48317946/how-to-upload-from-android-using-jsch-sftp – Omid1989 Jan 18 '18 at 10:55
1
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(gallery,PICK_IMAGE);
@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
         imageUri = data.getData();
         imageView.setImageURI(imageUri);
        }
    }

This will work. easy and simple

0

Have you enabled the permission in your app settings? (READ_EXTERNAL_STORAGE, or WRITE_EXTERNAL_STORAGE will both show up as 'storage')

Jayanth
  • 5,954
  • 3
  • 21
  • 38
abstractx1
  • 435
  • 6
  • 17