我有自定义列表视图,其中包含员工的姓名和用户名。我想删除任何员工。我使用上下文菜单删除了员工。 但是我没有在列表视图中获得所选项目的ID。 这是我的EmployeeDatabaseHelper类,其中包含deleteEmployee方法
EmployeeDatabaseHelper .java
public void deleteEmployee(String id){
SQLiteDatabase db = dbhelper.getReadableDatabase();
int delId = db.delete(TABLE_NAME_EMPLOYEE, id+" =? ",
new String[] {String.valueOf(id)});
db.close();
}
这里我使用上下文菜单删除员工
EmployeeFragment.java
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
menu.add(0,v.getId(),0,"Edit");
menu.add(0,v.getId(),0,"Delete");
}
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Edit"){
//ToDo edit employee Code
} else if (item.getTitle() == "Delete") {
new AlertDialog.Builder(getActivity())
.setTitle("Delete")
.setMessage("Are you sure you want to delete this Employee ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dbHelper.deleteEmployee(id);
//id is not getting here. (My issue)
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} else {
return false;
}
return true;
}
这是我的模型类Employee
Employee.java
public class Employee {
public String username;
public String name;
public String password;
}
答案 0 :(得分:0)
如果要删除ListView项,则应从适配器中删除此项目,用于此ListView。
答案 1 :(得分:0)
查看是否要使用ListView
从onCreateContextMenu
删除项目
你可以这样做:
int currentposition;
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
currentposition = info.position;
menu.setHeaderTitle("Choose");
menu.add(0, v.getId(), 0, "Delete ");
}
});
现在使用:
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
if (item.getTitle() == "Delete ") {
mArray.remove(currentposition);
ca.notifyDataSetChanged();
Toast.makeText(this, "Deleted ", Toast.LENGTH_SHORT)
.show();
}
return true;
}