I'm making an application that every time you press a button, change the text that is displayed by a random string. The strings are stored in an arraylist. The code I had so far was the following:
private TextView texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_game);
texto = (TextView) findViewById(R.id.textView);
}
public void cambiarMensaje(View v){
int aleatorio;
int total;
ArrayList<String> preguntas = new ArrayList<>();
preguntas.add("String 1");
preguntas.add("String 2");
...
int longitud = preguntas.size();
while(longitud > 0){
aleatorio = (int) (Math.random() * longitud);
String s = preguntas.get(aleatorio);
texto.setText(String.format(s));
preguntas.remove(aleatorio);
longitud--;
}
}
The problem is that every time you pressed the button, the arraylist was initialized with all the phrases again. I tried to solve it with the following changes:
private TextView texto;
ArrayList<String> preguntas = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_game);
preguntas.add("String 1");
preguntas.add("String 2");
...
texto = (TextView) findViewById(R.id.textView);
}
public void cambiarMensaje(View v){
int aleatorio;
int total;
int longitud = preguntas.size();
while(longitud > 0){
aleatorio = (int) (Math.random() * longitud);
String s = preguntas.get(aleatorio);
texto.setText(String.format(s));
preguntas.remove(aleatorio);
longitud--;
}
}
The problem now is that when I press the button a single phrase is shown (the button works only once). So my question is that I do not quite understand where I'm supposed to add the phrases to the arraylist and where I have to declare it, or if there is some way to fix the second code.