Android 中无法使用上下文菜单从列表视图中删除项目

Unable to delete item from List View using context menu in Android

我有自定义列表视图,其中包含员工的姓名和用户名。我正在尝试删除任何员工。我使用上下文菜单删除了员工。 但是我没有在列表视图中获得所选项目的 Id。 这是我的 EmployeeDatabaseHelper class,其中包含 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;
}

这是我的模特class员工

Employee.java

public class Employee {
    public String username;
    public String name;
    public String password;     
}

如果您想删除 ListView 项目,您应该从适配器中删除该项目,您正用于此 ListView。

查看是否要使用 onCreateContextMenuListView 中删除项目 你可以这样做:

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;
}