-1

i want to upload a image which i got from camera or browse it through my android gallery, however i got this error, i already search the error but i still got no clue why this happen, can u guys help me?

this is my error log :

 FATAL EXCEPTION: main   
 Process: com.example.jonatanmorisson.skripsi, PID: 971
 java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=971, uid=10140 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
 at android.os.Parcel.readException(Parcel.java:1599)
 at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
 at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
 at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
 at android.content.ContentResolver.query(ContentResolver.java:498)
 at android.content.ContentResolver.query(ContentResolver.java:441)
 at com.example.jonatanmorisson.skripsi.CameraGallery.getPath(CameraGallery.java:199)
 at com.example.jonatanmorisson.skripsi.CameraGallery.uploadMultipart(CameraGallery.java:111)
 at com.example.jonatanmorisson.skripsi.CameraGallery$2.onClick(CameraGallery.java:63)
 at android.view.View.performClick(View.java:5201)
 at android.view.View$PerformClick.run(View.java:21209)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5525)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

here's my activity code

public class CameraGallery extends AppCompatActivity {
    TextView txtnama;
    ImageView ivImage;
    Integer REQUEST_CAMERA=1, SELECT_FILE=0;
    private Button btnupload;
    private Uri filePath;
    private Bitmap bitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_gallery);


    txtnama = (EditText) findViewById(R.id.txtNama);
    ivImage = (ImageView) findViewById(R.id.ivImage);
    btnupload = (Button) findViewById(R.id.btnupl);

    final ImageButton fab = (ImageButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            SelectImage();
            fab.setVisibility(View.INVISIBLE);
        }
    });

    btnupload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadMultipart();
        }
    });
}

private void SelectImage(){

    final CharSequence[] items={"Camera","Gallery", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(CameraGallery.this);
    builder.setTitle("Add Image");

    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (items[i].equals("Camera")) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);

            } else if (items[i].equals("Gallery")) {

                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, SELECT_FILE);

            } else if (items[i].equals("Cancel")) {
                dialogInterface.dismiss();
            }
        }
    });
    builder.show();
}

public void uploadMultipart() {
    String name = txtnama.getText().toString().trim();
    String path = getPath(filePath);
    try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                .addFileToUpload(path, "image") //Adding file
                .addParameter("name", name) //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

@Override
public  void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode,data);
    if(resultCode== Activity.RESULT_OK){
        if(requestCode==REQUEST_CAMERA){
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");
            filePath = data.getData();
            try {
                ExifInterface exif = new ExifInterface(bitmap.toString());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                Log.d("EXIF", "Exif: " + orientation);
                Matrix matrix = new Matrix();
                if (orientation == 6) {
                    matrix.postRotate(90);
                }
                else if (orientation == 3) {
                    matrix.postRotate(180);
                }
                else if (orientation == 8) {
                    matrix.postRotate(270);
                }
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // rotating bitmap
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                ivImage.setImageBitmap(bitmap);
            }
            catch (Exception e) {
            }
        }else if(requestCode==SELECT_FILE){
            Uri selectedImageUri = data.getData();
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                ivImage.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

//method to get the file path from uri
public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_camera_gallery, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

and here's my androidmanifest code

<?xml version="1.0" encoding="utf-8"?>

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

<application
    android:allowBackup="true"
    android:icon="@drawable/bruno"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainMenu"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".CameraGallery" />
    <activity android:name=".TemuKembali"></activity>
</application>

i got no clue why this problem happens, i do some things like change the targeted sdk just like what i found in web but the problem still appears, i hope u guys can help me, thanks !!

  • 4
    Log says it clearly: "Permission Denial: requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()" - Declaring a permission in the manifest doesn't have to grant it by default. Go to the settings and check if it is actually granted and try to request it on app run time. Check this: https://developer.android.com/training/permissions/requesting.html?hl=en-419 – JMedinilla Oct 20 '17 at 06:53

4 Answers4

1

The Answer is in the question.

java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=971, uid=10140 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

Error is occurring because your program does not have permission to read a file.

bit-shashank
  • 887
  • 11
  • 27
0

You have to check and request permission at runtime for Android 6.0+

Check the documentation for more: https://developer.android.com/training/permissions/requesting.html

Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
0

Request runtime permission before uploading

if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) 
    {
      // Save your data in here
                    Log.e("callPhone: ", "permission" );
    } 
    else 
    {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                    Toast.makeText(this, "need permission", Toast.LENGTH_SHORT).show();
    }
Saneesh
  • 1,796
  • 16
  • 23
0

One way to avoid the issue is to make the targetSdkVersion lower than 23. Other way is to ask for permission in runtime. See answers here: Storage permission error in Marshmallow

Shahbaz Talpur
  • 315
  • 4
  • 17