Ad

How Do I Generate Random String Array Urls Without Repeating?

- 1 answer

I am trying to generate random string array urls in picasso, everything is working fine but it repeats, like i had 28 string array items when i start app some items are repeating but i want only 1 item at one time when random start

This is my code

     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random(); 
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);
Ad

Answer

You can keep track of previously generated integers in an array/list and check the array each time you generate a new random number. This way, if the new integer generated already exists in the array, you generate a new one, until you have generated 28 numbers, after which you will have to clear the array and start over.

ImageView imageView = itemView.findViewById(R.id.imageview);
Random random = new Random();
List<Integer> prevInts = new ArrayList<>();
Picasso.get().load(icons[randomUniqueInteger()]).into(imageView);

public int randomUniqueInteger(){
    int p = 0;
    do {
        p = random.nextInt(icons.length);
    } while(prevInts.contains(p));

    if ((prevInts.size + 1) == icons.length){
       prevInts.clear();
    }

    prevInts.add(p);

    return p;
}
Ad
source: stackoverflow.com
Ad