0

I need to randomly select an image from a user's photo gallery.

I don't mean starting an intent as in:

Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE);
admdrew
  • 3,790
  • 4
  • 27
  • 39
PHPupil
  • 785
  • 1
  • 7
  • 10

2 Answers2

1

I would do like that, but I don't think I can select all the gallery photos, I think that is impossible

File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File[] listFiles = picturesDirectory.listFiles();
Random r = new Random();
File randomPicture = listFiles[r.nextInt(listFiles.length)];
Uri pictureUri = Uri.fromFile(randomPicture);

Then you can use that Uri (or File) object to perform your action, for example load it into an imageView: mImageView.setImageUri(pictureUri);

Hope this will help! I remember that you won't select all pictures but only the pictures stored in that folder. In fact many applications save their pictures in other personal folders that could be inaccesible.

kevskree
  • 4,442
  • 3
  • 24
  • 32
rickyalbert
  • 2,552
  • 4
  • 21
  • 31
  • It works great for me I combined it: http://stackoverflow.com/a/21767418/2843455 but i have one more Question: How do I select only the files that are images? because it picks videos(.mp4) – PHPupil Oct 25 '14 at 06:36
  • See the following override of the listFiles method: http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter) – rickyalbert Oct 25 '14 at 12:29
0

Use this to get all the images and then the Java Random class to randomly select an index of the array. Once you have that you can request that specific image.

    //where contextObject is your activity
    ContentResolver cr = contextObject.getContentResolver();

    String[] columns = new String[] {
                    ImageColumns._ID,
                    ImageColumns.TITLE,
                    ImageColumns.DATA,
                    ImageColumns.MIME_TYPE,
                    ImageColumns.SIZE };
    cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    columns, null, null, null);

Code sample taken from here.

Community
  • 1
  • 1
FuegoFingers
  • 2,181
  • 6
  • 27
  • 36
  • typically add `"RANDOM()"` in the `sortOrder` parameter, take the first item, it's random! – njzk2 Oct 24 '14 at 18:32
  • I didn't even realize you could do this. OP follow njzk2's suggestion. I don't want to edit because I wont have a chance to test it and make sure my edit actually works but you should definitely try this out. – FuegoFingers Oct 24 '14 at 18:49
  • That assumes the query is going to be translated into an SQLite query. Nowadays it works, but it breaks the separation between the exposition layer and the storage layer. – njzk2 Oct 24 '14 at 18:52