0

on the below code data.size() is equal to 6 and i'm sure the "if" block inside it should be execute at last 3 times,but it's execute once,why??

 private void deletePost(){

    byte count=0;
    Log.v(TAG,"size "+data.size());
    for(int i=0;i<data.size();i++){
        if(data.get(i).isItemSelected()){
            data.remove(i);
        //    deleteFromCloud(data.get(i).getId());
            Log.v(TAG,"POS "+i);
            count++;
        }
        Log.v(TAG,"i  "+i);

    }
    Log.v(TAG,"items deleted "+count);
    rcAdapter.notifyDataSetChanged();
    Toast.makeText(this,count + " " + getString(R.string.itemsDeleted),Toast.LENGTH_LONG).show();

}
amir dt
  • 83
  • 2
  • 9
  • 3
    If you remove the current item, all the following items will be shifted, i.e. you might skip items because of this. Try doing it from the end instead. for (int i = data.size() - 1; i >= 0; i--) – Gennadii Saprykin Apr 23 '18 at 12:40
  • 3
    Iterate the list in reverse. – Andy Turner Apr 23 '18 at 12:40
  • Your title seems to have little to do with your actual problem... I'd suggest rephrasing. – NonameSL Apr 23 '18 at 12:41
  • You can use iterator to remove elements from ArrayList while iterating on it. `Iterator iterator = data.iterator(); while (iterator.hasNext()) { Data data = iterator.next(); if (data.get(i).isItemSelected()) { data.remove(i); // deleteFromCloud(data.get(i).getId()); Log.v(TAG, "POS " + i); count++; } Log.v(TAG, "i " + i); }` – xingbin Apr 23 '18 at 12:42
  • @amirdt This one `import java.util.Iterator;` – xingbin Apr 23 '18 at 12:53

0 Answers0