0

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);

    ...

}

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

No I got just one title, then another title, maybe an other title and then the title at the beginning.
I didn't get what you want to convey, can you please elaborate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.