问题
My current code to retrieve data from webservice is the following:
try{
for(int i = 0; i <= list.size() - 1; i++){
SoapObject request = new SoapObject(NAMESPACE + "/", "get_all");
request.addProperty("host", host);
request.addProperty("user", user);
request.addProperty("pass", pass);
request.addProperty("bd", bd);
request.addProperty("id", list.get(i));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 60000);
try {
androidHttpTransport.call(URL + "/get_all", envelope);
} catch (Exception e) {
Log.e("Error HH:", e.toString());
break;
}
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
JSONObject jb = (JSONObject) jr.get(0);
db.update_text(jb.getString("text_priority"), jb.getInt("id"));
updateLabel("Importing id: " + jb.getString("id"));
publishProgress((i * 100) / list.size());
}
}catch (Exception e) {
Log.e("Error H:", e.toString());
}
And it displays correctly in the label the following:
"Importing id: 1"
"Importing id: 2"
"Importing id: 3"
"Importing id: 4"
"Importing id: 5"
"Importing id: 6"
It works ok. Although, I would like to delete whenever the call is done perfectly the ID from the variable "list".
try {
androidHttpTransport.call(URL + "/get_all", envelope);
list.remove(list.get(i));
} catch (Exception e) {
Log.e("Error HH:", e.toString());
break;
}
But, with this code my label output is the following:
"Importing id: 1"
"Importing id: 3"
"Importing id: 5"
"Importing id: 7"
I also tried this:
try {
androidHttpTransport.call(URL + "/get_all", envelope);
list.remove(i);
} catch (Exception e) {
Log.e("Error HH:", e.toString());
break;
}
But I get the same result, anyone can tell me why? Thanks.
回答1:
You need to start at the last item in the list and and work backwards if you want to remove items at the same time you're iterating over them. So change your for loop to:
for(int i = list.size()-1; i >= 0; i--)
Since you're shifting everything over to the left when removing an item from an array, you want to make sure your cursor is moving in the same direction as well. So if we have an array of 4 items and are looking at the item in the 0th position:
[itemA itemB itemC itemD] (i=0)
^
then remove the item and increment our counter:
[itemB itemC itemD] (i=1)
^
we jumped right over itemB and went straight to itemC! But going from back to front:
[itemA itemB itemC itemD] (i = 3)
^
and removing:
[itemA itemB itemC] (i=2)
^
we didnt miss anything.
来源:https://stackoverflow.com/questions/19835278/android-delete-from-list-is-wrong