Show Image in Imageview

Asked

Viewed 378 times

0

I have a project that uses Fragments, I have a button that directs me to the image gallery, there I have to select an image and show in an image view, but I’m not getting.

btnGaleria.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent,0);

        }



    });


  @Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (requestCode == IMAGEM_INTERNA) {
        if (requestCode == IMAGEM_INTERNA && resultCode == Activity.RESULT_OK) {

            Uri imagemSelecionada = intent.getData();

            String[] colunas = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContext().getContentResolver().query(imagemSelecionada, colunas, null, null, null);
            cursor.moveToFirst();

            int indexColuna = cursor.getColumnIndex(colunas[0]);
            String pathimg = cursor.getString(indexColuna);
            cursor.close();

            Bitmap bitmap = BitmapFactory.decodeFile(pathimg);
            this.image_selecionada.setImageBitmap(bitmap);
        }
        else{
            Toast.makeText(getActivity(), "Imagem não existe!", Toast.LENGTH_SHORT).show();
        }

    }
}
  • If you are going to base what you posted here of the code ta bone, bro, see, start by checking two veses for "requestCode" in if (requestCode == IMAGEM_INTERNA) and then inside that if Voce checks again for it, then Voce uses this value contained in "IMAGEN_INTERNA" in the method public void onActivityResult(...) {...} Voce must pass this value by the call of the Intent and by what I could see Voce passes 0 by its Intent. checks that there and trains more expensive

1 answer

0

To access the mobile gallery is used a Intent android standard:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, CONSTANTE_ESCOLHIDO);

So you will receive in onActivityResult() the image chosen in the form of Uri:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null && resultCode == Activity.RESULT_OK && requestCode == CONSTANTE_ESCOLHIDO) {  
        Uri photoData = data.getData();      
    }
}

So you can turn this Uri in a Bitmap and place it in an Imageview:

photoBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoData);
photoView.setImageBitmap(photoBitmap);

Browser other questions tagged

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