1
I’m "playing" with the canvas (android) and I’m having trouble removing element from an Arraylist.
The app works like this: The user clicks on the screen, a ball appears that goes up but I want to remove only the balls that exceeded the limit y <= -50
. When I remove it generates this error:
09-08 23:28:12.617: E/AndroidRuntime(6719): FATAL EXCEPTION: Thread-2330
09-08 23:28:12.617: E/AndroidRuntime(6719): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
09-08 23:28:12.617: E/AndroidRuntime(6719): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
09-08 23:28:12.617: E/AndroidRuntime(6719): at java.util.ArrayList.get(ArrayList.java:304)
09-08 23:28:12.617: E/AndroidRuntime(6719): at com.dotjogoqualquer.JogoView.update(JogoView.java:50)
09-08 23:28:12.617: E/AndroidRuntime(6719): at com.dotjogoqualquer.JogoView.run(JogoView.java:40)
09-08 23:28:12.617: E/AndroidRuntime(6719): at java.lang.Thread.run(Thread.java:856)
Code
public void update() {
if (obj.size() >= 1){
for(int x = 0; x < obj.size(); x++) {
obj.get(x).y -= 15;
if (obj.get(x).y < -50) {
obj.remove(x); //Erro ocorre aqui
}
}
}
postInvalidate();
}
Links to the complete code
http://pastebin.com/hDz3nyzk (Line 48)
What if you try to use the object and not the index to perform the removal? , as in this example
– h3nr1ke
like this oh... public void update() { if (obj.size() >= 1){ for(int x = 0; x < obj.size(); x++) { obj.get(x). y -= 15; if (obj.get(x).y < -50) { obj.remove(obj.get(x)); // <<======================== HERE } } } postInvalidate(); }
– h3nr1ke
tried that which would be most correct (I think)
for(objetos _x : obj) {
 _x.y -= 15;
 if (_x.y < -50) {
 obj.remove(_x);
 }
 }
resulted in this error http://pastebin.com/QCLP0ipJ– Weslei Ramos
viche, now you are removing the item, but at the same time have people adding, who knows if you use synchronizedList
– h3nr1ke