Permission denied when accessing gallery image

Asked

Viewed 618 times

2

I need to allow the user to choose an image from the gallery and for that I am trying to get the application to request the user’s permission. I created the variable ok to give permission to the user, if it is all right, its value is set to true. But the ok never turns out to be true. My code:

public class EditarPerfil extends AppCompatActivity {
private Bitmap bitmap;
ImageView imgperfil;
boolean ok = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.editar_perfil);

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);


    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            callDialog("É necessário permitir que o aplicativo acesse a galeria");
        } else {
            //solicita permissão
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            ok = true;
        }
    }

    TextView alterarimg = (TextView) findViewById(R.id.alterarimg);

    alterarimg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carregarGaleria();
        }
    });

public void carregarGaleria() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 1);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    InputStream stream = null;
    if(ok) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            try {
                if (bitmap != null) {
                    bitmap.recycle();
                }
                stream = getContentResolver().openInputStream(data.getData());
                bitmap = BitmapFactory.decodeStream(stream);
                imgperfil.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (stream != null)
                    try {
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }

        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 0:
            //se a permissão for negada, o array de resultados estará vazio
            //verifica se tem permissão
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                ok = true;
            } else {
                ok = false;
            }
            break;
        default:
            break;
    }
}

private void callDialog(String message) {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Permission");
    dialog.setMessage(message);
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ok = true;
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog.show();
}

private void alert(String s) {
    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}

permissions in the manifest:

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

1 answer

1


Your code is very confusing, I think you never get the permission.

When your "dialog" opens and the user chooses "OK" you have to re-ask for permission.

Create a method to ask for permission:

private void getPermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        callDialog("É necessário permitir que o aplicativo acesse a galeria");
    } else {
        //solicita permissão
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

In the method in the onClick of alterarimg check if you have permission, if you have call carregarGaleria(); if you don’t ask for permission.

alterarimg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        getPermission()
    }
    else{
        carregarGaleria();
    }
});

When you receive permission, in the method onRequestPermissionsResult(), call back carregarGaleria();

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 0:
            //se a permissão for negada, o array de resultados estará vazio
            //verifica se tem permissão
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                carregarGaleria();
            } else {
                //A permissão foi negada
                //sai da acticity
                finish(); //ou não faça nada
            }
            break;
        default:
            break;
    }
}

In the dialog method, at the click of the "OK" button again ask for permissions:

private void callDialog(String message) {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Permission");
    dialog.setMessage(message);
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getPermission();
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog.show();
}

Delete the attribute boolean ok = false; don’t need it.

  • 2

    Boy, I figured out what it was, and I’m kind of embarrassed... it couldn’t be any more of a silly mistake. He had put the permission tags inside the manifest App. Thank you very much and sorry for taking your time! Thank you very much, you save my life in the forum :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.