Search code examples
androidimageviewgalleryandroid-gallery

Get any image from android phone gallery and use in a ImageView


I have an ImageView in my XML code and I want my application to open this ImageView filled with one of the images I have in my gallery (without I choose one).

I would also like this to work on any android phone (or most of them).

I was trying something like this.

principalActivity_iv_UltimaFoto = (ImageView) findViewById(R.id.principalActivity_iv_UltimaFoto);
File imagensGaleria = new File(Environment.getExternalStorageDirectory().getPath());
File[] listaImagens = imagensGaleria.listFiles();
principalActivity_iv_UltimaFoto.setImageURI(Uri.parse(listaImagens[0].toString()));

Thanks.


Solution

  • Ok. Finally I solved my question.

    First I create a cursor and get all the images I have in my gallery phone and get the last photo I took.

    Cursor cursor = pickLastPhotoAlbum();
    

    After I move the cursor to first line, get the quantity of lines the cursor returned and create a Drawable.

    cursor.moveToFirst();
    int qtd = cursor.getCount();
    Drawable backgroundGaleria;
    

    Third I made an if to see if my cursor is null or not.

    If is null I get a drawable image that I have in my imgs folder.

    If is not null I get the path of the image, set my drawable from path and set the background of my ImageView with this drawable.

    if (qtd > 0){
        String imageGallery = Environment.getExternalStorageDirectory()+ "/Tubagram/" + cursor.getString(1)+".png";
        backgroundGaleria = Drawable.createFromPath(imageGallery);
        principalActivity_iv_UltimaFoto.setBackground(backgroundGaleria);
    }else{
        principalActivity_iv_UltimaFoto.setBackgroundResource(R.drawable.box_imagem_album);
    }
    

    To the image doesn't overflow his size you need to set the width and height (I set min, normal size and max) using XXXdp.

    android:layout_width="61dp"
    android:layout_height="42dp"
    

    And here is the method who returns values to my cursor

    private Cursor pickLastPhotoAlbum(){
        final ContentResolver cr = getContentResolver();
    final String[] p1 = new String[] {
        MediaStore.Images.ImageColumns._ID,
        MediaStore.Images.ImageColumns.TITLE,
        MediaStore.Images.ImageColumns.DATE_TAKEN
    };
    Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
    
    if (c1.moveToFirst() ) {
        Log.i("Teste", "last picture (" + c1.getString(1) + ") taken on: " + new Date(c1.getLong(2)));
    }
    
        Log.i("Caminho download imagem", "file://"+Environment.getExternalStorageDirectory()+ "/Tubagram/"  + c1.getString(1) + ".png");
    
    return c1;
    }
    

    Thanks to everyone who helped me with this.