Permission denied when accessing gallery image [duplicate]

2

I need to allow the user to choose an image from the gallery and for this I'm trying to get the application to ask the user for permission. I created the variable ok to give the user permission, if everything is right, its value is set to true . But ok never gets to 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 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"/>
    
asked by anonymous 22.08.2016 / 19:21

1 answer

1

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

When your "dialog" is opened and the user chooses "OK" you must ask for permission again.

Create a method to request 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 method no% wont changeimg make sure you have permission, if you have call onClick if you do not request the 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 the permission, in method carregarGaleria(); , call onRequestPermissionsResult()

@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, in the click of the button "OK" ask for the permissions again:

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 carregarGaleria(); attribute you do not need.

    
22.08.2016 / 20:31