vendredi 25 mars 2016

Random activity without repetition

I already read hundreds of posts here about it but none is adapted to my simple needs. NOOB ALERT.

I'm trying to have a notification in my app choose from a list of activities and open one of them randomly but without repetition, I was able to have a randomized effect but some activities pop up many times and others don't.

So basically what I need is to go over all the activities on the list randomly, and when all of them have been visited, re-shuffle the list and start over

Here's a little example I cooked up: one button that takes me to 10 activities:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button randomBtn;
        randomBtn = (Button) findViewById(R.id.randomBtn);
        randomBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ArrayList<Class> activities = new ArrayList<>();
                activities.add(Activity01.class);
                activities.add(Activity02.class);
                activities.add(Activity03.class);
                activities.add(Activity04.class);
                activities.add(Activity05.class);
                activities.add(Activity06.class);
                activities.add(Activity07.class);
                activities.add(Activity08.class);
                activities.add(Activity09.class);
                activities.add(Activity10.class);

                Collections.shuffle(activities);

                Intent intent = new Intent(MainActivity.this, activities.get(0));
                startActivity(intent);

            }
        });
    }
}

The results are like this: First run: 04, 07, 07, 05, 03, 09, 06, 09, 04, 01

Second run: 07, 04, 10, 02, 05, 06, 10, 05, 02, 08.

I just can't seem to find it.

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire