我的ListView
中有一个奇怪的问题,我不明白为什么会发生。
在我的checklist
中,当我选择3个或更多项目时,仅删除最后一个和第一个项目,不删除第二个项目。它只是保持选中状态,我需要再次单击此发布按钮。
SendDataFragment活动
btn_DataSend=(Button) getActivity().findViewById(R.id.trn_post_btn);
btn_DataSend.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
//get All info like custID, mStatus mTrnNo mCustID mCustName
List<customerInfo> stateList = adapter.mCategories;
for(int i=0;i<stateList.size();i++)
{
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
//postData(state.getmTrnNo());
int c = i;
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
}
}
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), responseText, Toast.LENGTH_LONG).sho();
}
});
DBManager
public void delete_ShipmentDetails(String id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("delete from "+ DatabaseHelper.TBL_OE_SHIPMENT_H +" WHERE " +DatabaseHelper.OE_SHIPMENT_H_CUSTID+"="+id);
}
我的应用程序的屏幕截图是:
答案 0 :(得分:1)
以相反的顺序使用循环
for(int i = stateList.size()-1; i >= 0; i--){
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
//postData(state.getmTrnNo());
int c = i;
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
notifyItemRemoved(i);
}
}
adapter.notifyDataSetChanged();
答案 1 :(得分:1)
这是因为您正在循环浏览列表,同时更改列表的长度。
有几种方法可以解决此问题,既可以向后循环遍历列表,也可以使用迭代器或将删除的内容保存到最后。为了将循环更改为使用迭代器,以下各项应按预期工作:
Iterator<Integer> it = stateList.iterator();
while (it.hasNext()) {
customerInfo state = it.next();
if(state.ismStatus()) {
dbManager.delete_ShipmentDetails(state.getmCustID());
it.remove();
}
}
adapter.notifyDataSetChanged();
答案 2 :(得分:0)
现在我明白了,我也做了另一种方式,就像
for(int i=0;i<stateList.size();i++)
{
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
postData(state.getmTrnNo());
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
});