Reputation: 179
In a activy I have written code that works correctly.
But now I have added a method to this activity with the following code:
private void obtenerDatosReuniones(){
try {
int j=0;
String aux = jsonReuniones.getString("nombres");
String aux2 = null;
aux2 = aux.replace("[", "");
aux2= aux2.replace("]", "");
String [] campos = aux2.split(",");
while(j<campos.length){
nombres_reuniones.add(campos[j]);
}
the type of nombres_reunones is ArrayList
When I run the application appears out the following error on line nombres_reuniones.add (campos [j]):
What am I doing wrong?
Thanks!
Upvotes: 2
Views: 1464
Reputation: 236004
You're not advancing the loop:
while (j < campos.length) {
nombres_reuniones.add(campos[j]);
j++; // without this, you'll loop forever!
}
What's happening is that you're adding an infinite amount of "campos" to the ArrayList
, exhausting all the memory available to your program in the process.
Remember: a loop's condition must be false
at some point for the loop to end. If you forget to advance the loop (in this case, by incrementing the j
variable) the condition will always be true
and the loop will never exit, therefore creating an infinite loop.
Upvotes: 3
Reputation: 199215
You are not updating the value of j
hence j
is always 0
and always smaller than campos.length
Upvotes: 0
Reputation: 1500405
Look at your loop:
while(j<campos.length){
nombres_reuniones.add(campos[j]);
}
How do you anticipate that ever finishing? You don't modify j
. Given that you don't make any change to j
after declaring it and assigning it a value of 0
right at the start, it would be much clearer as:
for (int j = 0; j < campos.length; j++) {
nombres_reuniones.add(campos[j]);
}
Or better:
for (String item : campos) {
nombres_reuniones.add(item);
}
Or even simpler:
nombres_reunions.addAll(Arrays.asList(campos));
Additionally, your earlier code can be simpler. Look at this:
String aux2 = null;
aux2 = aux.replace("[", "");
aux2= aux2.replace("]", "");
Why bother assigning aux2
an initial value of null
which you then immediately overwrite? Additionally, you can easily chain the method calls. It would be neater as:
String aux2 = aux.replace("[", "").replace("]", "");
And in fact, you can just chain the whole of the string manipulation together from start to finish:
String[] campos = jsonReuniones.getString("nombres")
.replace("[", "")
.replace("]", "")
.split(",");
nombres_reunions.addAll(Arrays.asList(campos));
(I'd stop there, rather than inlining even that expression...)
Upvotes: 3