Reputation:
I have the following situation:
I have an array with 245 String
items. Now I have a Button
which gives me a random String
from the array when clicked. But then, I get repetition like after one string, the previous string comes. How to fix it?
Here is the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
Resources res = getResources();
titles = res.getStringArray(R.array.title_array);
String q = titles[rgenerator.nextInt(titles.length)];
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(q);
...
}
Upvotes: 0
Views: 92
Reputation: 3826
First convert your words array to arraylist
ArrayList<String> wordsList = new ArrayList<String>(Arrays.asList(titles));
Then create another list which holds the words that have already printed
ArrayList<String> usedList = new ArrayList<String>();
Then when you get a word just remove it from wordlist and move it to usedlist
String s = wordsList.get(rgenerator.nextInt(wordsList.size()));
wordsList.remove(s);
usedList.add(s);
Upvotes: 1