I have used this question here on stackoverflow to create a random string without problem 😀
( Show random string)
Some times the same string shows up and that’s annoying.
So I want the string to only show one time per session, I have already a Quit Session button that kills the class. So lets say I have numbers from 1-3. Number 2 shows up first, then 1, becuase there’s only one number left only 3 can be shown.
My button code for the “next button”. Currently it kills the class and starts it again! How can I change it so it just displays a new string?
private void onButtonClick(Button clickedButton) {
Intent startIntent = null;
if (clickedButton.getId() == R.id.quit) {
startIntent = new Intent(this, mainmenu.class);
finish();
}
else if (clickedButton.getId() == R.id.next) {
startIntent = new Intent(this, play.class);
startActivity(startIntent);
finish();
}
if (startIntent != null) {
startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityIfNeeded(startIntent, 0);
}
}
private void setupbutton() {
View.OnClickListener onClickHandler = new View.OnClickListener() {
public void onClick(View v) {
onButtonClick((Button)v);
}
};
Button button = (Button)findViewById(R.id.quit);
button.setOnClickListener(onClickHandler);
button = (Button)findViewById(R.id.next);
button.setOnClickListener(onClickHandler);
The same string is appearing because the random number generator generates random numbers! It could generate the same number multiple times in a row.
There are many possibilities, to name two:
Put all strings in an array and shuffle it. Then take the elements out one by one starting with index one:
Put all strings in an array, select a string with a random index and remove the string:
EDIT:
Ok, I see…
You have to remember which strings have not been used already. Store the strings in a List and make the list static, so you can save state between the creation of different instances of the Activity
play:Then change your constructor a bit: