Skip to content

Instantly share code, notes, and snippets.

@tsohr
Last active September 17, 2021 04:41
Show Gist options
  • Save tsohr/5683178 to your computer and use it in GitHub Desktop.
Save tsohr/5683178 to your computer and use it in GitHub Desktop.
Get an image resource from external content resolver randomly in Android.
protected static Uri getRandomExternalImageContent(Context c) {
ContentResolver resolver = c.getContentResolver();
if (resolver == null)
return null;
String [] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
int count = cursor.getCount();
int position = (int) (Math.random() * count);
if (! cursor.moveToPosition( position ) ) {
return null;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String path = cursor.getString(column_index);
cursor.close();
return Uri.fromFile(new File(path));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment