Reputation: 105
I am trying to remove the last element of arraylist
after every 10 minutes.
I am using this code to do that:
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
array.remove(array.size() -1); //array is my ArrayList object
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 600000); //execute in every 10 minutes
But it is giving IndexOutOfBoundsException
.Can anyone solve this problem.
Upvotes: 0
Views: 6032
Reputation: 12715
//check if its null or not when debugging
if(array!=null){
//Log something thats it is not null at this point
if(array.size()>0){
array.remove(array.size() -1);
}
else{
//Log the array is empty
}
}
Upvotes: 0
Reputation: 115
You have an empty array as @TheAndroidDev said. What about to use Rx, something like this:
Observable.from(array)
.interval(10, TimeUnit.MINUTES)
.map(i -> array.size() > 0 ? array.remove(array.size() - 1) : null)
.take(array.size())
.subscribe(integer -> {
// Do something with the integer or type you use
});
Upvotes: 0
Reputation: 5639
You are getting IndexOutOfBounds because you are trying to remove an item that isn't there, so you should perform a check on your removal to stop the removal if there is nothing there:
if(array.size() > 0){
array.remove(array.size() -1);
}
Upvotes: 4