Set ImageView content by means of a URI

1

I'm trying to set the ImageView image of my second Activity through a URI that comes from the first Activity but so far without success. What could be wrong?

File diretorio = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

      String nomeImagem = diretorio.getPath() + "/" + System.currentTimeMillis()+".jpg"; 

      uri = Uri.fromFile(new File(nomeImagem)); 

@Edit

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
    startActivityForResult(intent,CAPTURAR_IMAGEM);

 public void chamarTela(){
    Bundle dados = new Bundle();
    dados.putString("foto",uri.getPath().toString());
    Intent intent = new Intent(this,TelaPraVerImagem.class);
    intent.putExtras(dados);
    startActivity(intent);
}


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

    imageView = (ImageView) findViewById(R.id.foto);
    //imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
   // TextView textView = (TextView)findViewById(R.id.mensagem);
    Intent intent = getIntent();
    if (intent != null){
        if(intent.getExtras() != null){
           Bundle dados = intent.getExtras();
           String  imgpath = dados.getString("foto");
           Uri uri = Uri.parse(imgpath);
           imageView.setImageURI(uri);


        }
    }
}
    
asked by anonymous 05.09.2014 / 22:38

1 answer

2
Using setImageUri () is not the best way to set an image in your UI, it can cause some latency failures at the time of decode.

Instead, use setImageBitmap () :

//Transforme sua URI em um Bitmap
Bitmap myImg = BitmapFactory.decodeFile(uri.getPath()); 
imgView.setImageBitmap(myImg);

@Edit

I suspect that getPath () is not returning the true path of your image. When you access the path via getPath () , the return would be something like this:

. \ file \ image.jpg

PS: The URI class implements a Parcelable, that is, you can extract it directly from your intent.

Try this:

public void chamarTela(){
    Intent intent = new Intent(this,TelaPraVerImagem.class);
    intent.putExtra("foto", uri);
    startActivity(intent);
}

...
Intent intent = getIntent();
    if (intent != null){
        if(intent.getExtras() != null){
            Uri uri = intent.getParcelableExtra("foto");
            Bitmap myImg = BitmapFactory.decodeFile(uri.getPath().getAbsolutePath()); 
            imgView.setImageBitmap(myImg);
        }
    }

@ Edit2

Following the Google documentation , I think you're actually putting the wrong path when it comes to creating the image

Follow the code with some comments:

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Criando o nome de uma imagem. Você pode seguir o padrão Brasil aqui
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    //Um detalhe aqui, não é garantido que o device tenha um getExternalStoragePublicDirectory(), 
    //É importante você fazer esta validação
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefixo */
        ".jpg",         /* sufixo */
        storageDir      /* diretorio */
    );

    // Esse é o path que você vai utilizar na resposta da sua Intent
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}


static final int REQUEST_TAKE_PHOTO = 1;

private void chamarTela() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Criando um File que aponta onde sua foto deve ir
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            ...
        }
        // Continua apenas se sua foto foi salva de verdade
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

private void setPic() {
    // Pegando as dimensões de sua View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // Pegando as dimensões do Bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determinando o quanto que deve diminuir de tamanho/qualidade
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Garantindo que o Bitmap fique boa dentro de uma View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    imgView.setImageBitmap(bitmap);
}
    
05.09.2014 / 22:49