Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a random picture from phone gallery and display in view

Is there a possibility to access the phone gallery, select a random image and display it on the view? i.e. have the entire process done without user intervention, having to pick an image or sending a uri, etc.

Thanks!

like image 502
n00b programmer Avatar asked Jun 12 '13 19:06

n00b programmer


1 Answers

The following snippet retrieve the gallery`s content and put every image path inside an array list. Then it choose randomly one of the path inside the ArrayList and put as resources for an ImageView

Handler handler = new Handler();

protected int counter = 0;
private ImageView mImageView;
private Bitmap currentBitmap = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image);
    mImageView = (ImageView) findViewById(R.id.imageView);
    String[] projection = new String[]{
            MediaStore.Images.Media.DATA,
    };

    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Cursor cur = managedQuery(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();
    handler.post(new Runnable() {
        @Override
        public void run() {
            int number = random.nextInt(count);
            String path = imagesPath.get(number);
            if (currentBitmap != null)
                currentBitmap.recycle();
              currentBitmap = BitmapFactory.decodeFile(path);
            mImageView.setImageBitmap(currentBitmap);
            handler.postDelayed(this, 1000);
        }
    });

}
like image 94
Blackbelt Avatar answered Nov 14 '22 08:11

Blackbelt