Last active
September 17, 2021 04:41
-
-
Save tsohr/5683178 to your computer and use it in GitHub Desktop.
Get an image resource from external content resolver randomly in Android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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