我有一个地址数据库。我只是希望用户能够删除一行,但列表不会更新。我见过所有其他人的例子,但他们不适合我。我一直在尝试各种不同的东西。它们都没有效果。我必须改变活动,然后删除。
我在一个活动中添加地址,并以finish();
结束 public void onItemClick(AdapterView <?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
db = new DatabaseHandler(this);
db.addAddress(str);
Intent intent= new Intent();
setResult(RESULT_OK, intent);
finish();
}
这是我对mylistview的deleteAddress(),我在简历中使用它。
private void deleteAddress(){
listview= (ListView)findViewById(R.id.listView);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> a, View v, int position, long id) {
final String selectedID = String.valueOf(position);
AlertDialog.Builder adb=new AlertDialog.Builder(Address.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.deleteAddress(selectedID);
updateList();
}});
adb.show();
return true;
}
});
}
public void updateList(){
dbHelper.fetchAllAddresses();
dataAdapter.notifyDataSetChanged();
这是我在数据库中的deleteAddress
public void deleteAddress(String rowId) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_CONTACTS, //table name
"_id"+"=?", // selections
new String[] {rowId}); //selections args
// 3. close
db.close();
}
这是我的listview
public void onResume() {
super.onResume();
deleteAddress();
cursor= dbHelper.fetchAllAddresses();
String columns[]= new String[]{
dbHelper.KEY_NAME
};
int[] to = new int[] {
R.id.rowTextView,
};
dataAdapter= new SimpleCursorAdapter(
this,R.layout.simplerow, cursor,columns,to,0);
dataAdapter.notifyDataSetChanged();
listview= (ListView)findViewById(R.id.listView);
listview.setAdapter(dataAdapter);
}
答案 0 :(得分:1)
您在position
方法中使用deleteAddress
作为行ID,但您应该id
,onItemClick
的参数。变化
final String selectedID = String.valueOf(position);
与
final String selectedID = String.valueOf(id);
答案 1 :(得分:0)
你的适配器看起来怎么样?您需要删除adapters-item-list中的项目,而不仅仅是在数据库中...执行该操作然后调用notifyDataSetChanged()!
答案 2 :(得分:0)
我没有更正您的代码,因为有很多可以修复,只是以您的方式提供您的答案,试试这个
public void updateList(){
cursor= dbHelper.fetchAllAddresses();
String columns[]= new String[]{
dbHelper.KEY_NAME
};
int[] to = new int[] {
R.id.rowTextView,
};
dataAdapter= new SimpleCursorAdapter(
this,R.layout.simplerow, cursor,columns,to,0);
listview.setAdapter(dataAdapter);
}