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!
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);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With