How to make a function that never chooses the same image twice


I'm trying to make a function that generate random images, but never twice and it goes until there are no images left.

In my case, there are 15 image files in drawable, and I want them to all be shown but without repeating.

package com.example.commander;

import java.util.Random;
import android.os.Bundle;

import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;

protected void onCreate(
    final Bundle savedInstanceState)

    img = (ImageView) findViewById(;
    btnRandom = (Button) findViewById(;

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
    if (ResourceID == 0)
        throw new IllegalArgumentException
            "No resource string found with name " + resName
        return ResourceID;

ArrayList<Integer> imageId = new ArrayList<Integer>();

 public void clickHandler(final View v)

                if (!btnRandom.isEnabled())

               int indeks = rnd.nextInt(14);

                final String str = "img_" + indeks;
                    getResources().getDrawable(getResourceID(str, "drawable",


public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(, menu);
    return super.onCreateOptionsMenu(menu);


public void goBack(View v){
    startActivity(new Intent(this, MainActivity.class));

public void onBackPressed() {


insert all image id to one list, use AndroidWarriors answer for generate one random number, get that image and remove from list, call more time until size of your list became 0

you can use following code:

ArrayList<Integer> imageId = new ArrayList<Integer>();
// insert your id here


  int index ;
     while (imageId.size() > 0)
      index =  randomInt(0 , imageId.size());

     /// do what you want with this index



and randomInt

public int randomInt(int min, int max) {

    Random randNumber = new Random();

    int randomNumber = randNumber.nextInt((max - min) + 1) + min;

    return randomNumber;