我在Android中创建了一个列表视图。我的listview数据来自sqlite数据库。当用户单击列表中的项目时。将出现用于删除确认的警报对话框。 这是我从列表中删除的代码:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(todaycode.this);
alertDialog.setTitle("Delete from list");
alertDialog.setMessage("Are you sure to delete?");
final int del_position=position;
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
//delete from database
mDb.deleteContact(list_food.get(+ del_position).getId());
//reload
final ArrayList<food_object> list_food = mDb.getAllfood();
final ListView list;
final String[] food_name = new String[list_food.size()];
for(int i=0;i<list_food.size();i++){
food_name[i]=list_food.get(i).getName();}
Integer[] imageId = {
R.drawable.image1,};
final customlist adapter = new customlist(todaycode.this, food_name, imageId);
list=(ListView)findViewById(R.id.listToday);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
这是我在DBAdapter中从我的数据库中删除的代码:
public boolean deleteContact(int id)
{
return db.delete(TABLE_NAME, COL_ID + "=" + id, null) > 0;
}
这段代码很有用。但有时用户无法从列表中删除项目,直到他们重新加载此活动(转移到其他活动并返回)。出现“警报”对话框,但在用户单击“是”后,没有任何反应。
这只会在某个时候发生。并且只在列表中的一个项目中出现,因此如果用户选择要删除的列表中的其他项目,它仍然有效。有人知道为什么会这样吗?
EDITED
经过多次尝试后,我得出结论,用户删除第二项(用户连续删除)后始终启动错误(项目无法删除),我仍然不知道为什么会这样做
这是我的DBAdapter代码,我将其简化为See the Code
这是我的自定义代码See the Code
答案 0 :(得分:1)
问题是您可能在表中使用自动增量ID。当你从setOnItemClick获取id时,它实际上是项的索引而不是id。因此,当您在索引3处删除一个ID将被删除时,并且下次您想要在同一索引处删除时,将不会有一个项目名称为whit。
答案 1 :(得分:0)
把这个听众放在那里然后兄弟..!
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
//delete from database
mDb.deleteContact(list_food.get(+ del_position).getId());
//reload
final ArrayList<food_object> list_food = mDb.getAllfood();
final ListView list;
final String[] food_name = new String[list_food.size()];
for(int i=0;i<list_food.size();i++){
food_name[i]=list_food.get(i).getName();}
Integer[] imageId = {
R.drawable.image1,};
final customlist adapter = new customlist(todaycode.this, food_name, imageId);
list=(ListView)findViewById(R.id.listToday);
list.setAdapter(null);
list.setAdapter(adapter);
}
});