jeudi 3 décembre 2015

Get new random image when button is clicked - android

I am developing an app that once a button is clicked I go to a new activity where 3 random images are set to an imageView. If the user does not like the 3 images selected, they can then click a button to generate 3 new random images. I am having two problems...

  1. I have the imageView set to a specific size but when the images show up they are sometimes smaller and are showing horizontally. I would like them to show up vertically and all as the size of the imageView. How do I change the code to do this?

  2. I am getting the new images to show up when I click the button but I am getting an error saying that I am running out of memory after I do it a few times. How do I change the code so I stop using all my memory?

Here is my code

public ImageView shirts;
public ImageView pants;
public ImageView shoes;
Button reload;
private Bitmap currentBitmap = null;
String[] projection = new String[]{
        MediaStore.Images.Media.DATA,
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.suggested_outfit);
    shirts = (ImageView)findViewById(R.id.shirtImage);
    pants = (ImageView)findViewById(R.id.pantsImage);
    shoes = (ImageView)findViewById(R.id.shoesImage);

    shirts.setImageBitmap(getImage());
    pants.setImageBitmap(getImage());
    shoes.setImageBitmap(getImage());

    reload = (Button)findViewById(R.id.getNewOutfit);
    reload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
            startActivity(getIntent());
        }
    });
}


public Bitmap getImage () {
    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Cursor cur = getContentResolver().query(images,
            projection,"", null, ""
    );
    final ArrayList<String> imagesPath = new ArrayList<String>();
    if (cur.moveToFirst()) {

        int dataColumn = cur.getColumnIndex(
                MediaStore.Images.Media.DATA);
        do {
            imagesPath.add(cur.getString(dataColumn));
        } while (cur.moveToNext());
    }
    cur.close();
    final Random random = new Random();
    final int count = imagesPath.size();
    int number = random.nextInt(count);
    String path = imagesPath.get(number);

    currentBitmap = BitmapFactory.decodeFile(path);

    return currentBitmap;
}

}

I read that it isn't good practice to reload the activity but I can't figure out a way to generate 3 new random images. I am open for any suggestions if there is a better way to do this.




Aucun commentaire:

Enregistrer un commentaire