@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.popup_layout, menu); return true; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.viewcontents_layout); ListView listView = findViewById(R.id.listView); myDB = new DatabaseHelper(this); final MenuItem deleteItem, editItem; final ArrayList theList = new ArrayList<>(); final Cursor data = myDB.getListContents(); final ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList); listView.setAdapter(listAdapter); deleteItem = findViewById(R.id.delete_item); editItem = findViewById(R.id.edit_item); final ListView finalListView = listView; listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView parent, View v, final int position, final long id) { PopupMenu p = new PopupMenu(ViewListContents.this, v); MenuInflater inflater = p.getMenuInflater(); inflater.inflate(R.menu.popup_layout, p.getMenu()); p.show(); //Listener wait for the click on the popup menu item p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show(); switch (item.getItemId()) { case R.id.delete_item: finalListView.getItemAtPosition(position); myDB.deleteEntry(finalListView.getSelectedItemPosition()); ((ArrayAdapter) listAdapter).remove(listAdapter.getItem(position)); ((ArrayAdapter) listAdapter).notifyDataSetChanged(); int x = ReadID(position); myDB.deleteEntry(x); myDB.getAllItems(Contract.YourEntry.COL2); return true; case R.id.edit_item: getTheme(); return true; default: return true; //return ViewListContents.super.onOptionsItemSelected(deleteItem); /* @Override public boolean onOptionsItemSelected() { switch (item.getItemId()) { case R.id.delete_item: theList.remove(position); return true; case R.id.edit_item: getTheme(); return true; default: return ViewListContents.super.onOptionsItemSelected(deleteItem); /* deleteItem.setOnActionExpandListener("Ok", new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { theList.remove(position); finalListView.setAdapter(listAdapter); });*/ return true; if (data.getCount() == 0) { Toast.makeText(ViewListContents.this, "Your list is empty :(", Toast.LENGTH_LONG).show(); } else { while (data.moveToNext()) { theList.add(data.getString(1)); listView.setAdapter(listAdapter); public int ReadID(int position){ DatabaseHelper mDbHelper = new DatabaseHelper(this); SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = {Contract.YourEntry.COL2}; String sortOrder = Contract.YourEntry.COL2 + " ASC"; Cursor cursor = db.query( Contract.YourEntry.TABLE_NAME, // The table to query null, // The array of columns to return (null to get all) null, // The columns for the WHERE clause null, // The values for the WHERE clause null, // null if you don't want to group the rows null, // null if you don't want filter by row groups sortOrder // the order try { int idColumnIndex = cursor.getColumnIndex(Contract.YourEntry.intWhereToGoListOID); int currentID = 0; int count = 0; while ((cursor.moveToNext() == true) && (count != (position + 1))) { currentID = cursor.getInt(idColumnIndex + 1); count ++; return currentID; } finally { cursor.close();

这是我的DB代码。

    public class DatabaseHelper extends SQLiteOpenHelper {
    // DATABASE
    public static final String DATABASE_NAME = "mylist.db";
    // TABLES
    public static final String TABLE_TWHERETOGOLIST = "TWhereToGoList";
    public static final String TABLE_NAME_2 = "TCategories";
    public static final String TABLE_TListDefiniton = "TListDefinition";
    // COLUMNS FOR TABLE: TWhereToGoList
    public static final String intWhereToGoListOID = "WhereToGoListOID";
    public static final String COL2 = "COL2";
    public static final String intCategoriesOID = "CategoriesOID ";
    public static final DateFormat dtDateLastModified = DateFormat.getDateInstance();
    Date c = Calendar.getInstance().getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
    public String formattedDate = df.format(c);
    public static final String strDescription = "Description";
    public static final String strGoogleLink = "GoogleLink";
    public static final Integer bVisited = 0;
    public static final Integer bRecommend = 0;
    public static final Integer intListDefinitionOID = 0;
    // COLUMNS FOR TABLE: TCategories
    public static final Integer getIntListDefinitionOID = 0;
    //public static final String strTitle = "strTitle";                 // Both can get called from the top
    //public static final String strDescription = "strDescription";     // Both can get called from the top
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.deleteDatabase(new File(DATABASE_NAME));
        String createTable = "CREATE TABLE " + TABLE_TWHERETOGOLIST + " (intWhereToGoListOID INTEGER PRIMARY KEY AUTOINCREMENT, "
                + " COL2 TEXT, " + " intCategoriesOID TEXT, " + " strDescription TEXT, "
                + " strGoogleLink TEXT, " + " bVisited INTEGER)";
        db.execSQL(createTable);
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(String.format("DROP IF TABLE EXISTS ", TABLE_TWHERETOGOLIST));
        onCreate(db);
    public boolean addData(String string) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, string);
        long result = db.insert(TABLE_TWHERETOGOLIST, null, contentValues);
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
    public Cursor getListContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_TWHERETOGOLIST, null);
        return data;
    /*public int delete(int position) {
        SQLiteDatabase db = this.getWritableDatabase();
        if (db == null) {
            Logger.getLogger("The DB is empty");
        db.delete(TABLE_TWHERETOGOLIST, COL2 + " = ?", new String[]{ (intWhereToGoListOID) }); //new String[]{Long.toString(positionOfId)} );

另一个更新。
问题可能是你在这句话的最后一行看到的-1。
如果我在点击删除按钮后在那里写一些其他的东西,并从主活动中再次回到列表中,文本被数字取代,一些元素被删除,其他元素得到一个数字或一些文本,我可以写到-1。
在另一种情况下,如果我再多看几遍这个细胞,数字就会变得很概括,让人觉得很恐怖。

public void deleteEntry(int position) {
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        sqLiteDatabase.execSQL("DELETE FROM " + Contract.YourEntry.TABLE_NAME + " WHERE " +
                Contract.YourEntry.COL2 + " = " + position + ";");
        sqLiteDatabase.execSQL("UPDATE " + Contract.YourEntry.TABLE_NAME + " SET " + Contract.YourEntry.COL2 +
                " = " + Contract.YourEntry.COL2 + " -1 " + " WHERE " + Contract.YourEntry.COL2 + " > " + position + ";");
        Logger.getLogger("Successfully deleted the item!!!");
        //Logger.getLogger(String.valueOf(getListContents()));
        db.close();
        return 1;
    public Cursor getAllItems() {
        SQLiteDatabase db = getReadableDatabase();
        return db.query(
                TABLE_TWHERETOGOLIST,
                null,
                null,
                null,
                null,
                null,

如果你有任何问题,请在下面的评论中问我。 谢谢你的回答 :)

更新1.0。

我现在遇到的问题是,我不知道如何才能在出现的弹出窗口中取得我长点击并按下删除的ListView项目的ID。

我必须把这个ListView项目的(ID什么的)拿到我的DB代码中来删除这个项目。

如果你有问题,请提出。

请详细描述 :) 我不知道我如何能做到这一点

5 个评论
我恐怕不明白?
Noah
@EyosiyasBerketab 我想在我的应用程序中删除一个ListView项目,同时按下弹出的删除部分。但我无法删除该项目。
Does myDB.delete(theList.get(position)); delete the record?
首先进行测试,之后你必须通知适配器数据已被更改。
Noah
现在它被1/2解决了,因为我现在有一个问题,我的整个列表被删除。 【替换代码0 @IntelliJAmiya
java
android
sqlite
listview
Noah
Noah
发布于 2020-10-09
1 个回答
Riccardo S.
Riccardo S.
发布于 2020-10-09
0 人赞同

当你点击删除时,你必须调用delete函数,并将你想删除的元素的ID传递给这个函数。
为了做到这一点,你必须将这些元素读入database,并挑选出你所选择的那一个。
我认为有一个问题应该是,position是从零开始的,而进入数据库的元素是从位置1开始的,所以你必须考虑这个问题。

这应该是读取元素的功能。
(Check this更多信息,可能对你有用)

更新:由于你使用的是一个合同类,所以进行了调整

    public int ReadID(int position){
         mDbHelper = new YourDbHelper(this);
         SQLiteDatabase db = mDbHelper.getReadableDatabase();
         String[] projection = {BaseColumns.intWhereToGoListOID,
         String sortOrder = YourEntry.intWhereToGoListOID+ " ASC";
         Cursor cursor = db.query(
                 YourEntry.TABLE_NAME,   // The table to query
                 projection,             // The array of columns to return (null to get all)
                 null,              // The columns for the WHERE clause
                 null,              // The values for the WHERE clause
                 null,              // null if you don't want to group the rows
                 null,              // null if you don't want filter by row groups
                 sortOrder          // the order
         try {
         int idColumnIndex = cursor.getColumnIndex(YourEntry.intWhereToGoListOID);
             int currentID  = 0;
             int count=0;
         while ((cursor.moveToNext() == true) && (count != (position + 1))) {
             currentID = cursor.getInt(idColumnIndex);
             count ++;
         return currentID;
         } finally {
        cursor.close();
为了更清楚地说明问题,请使用一个合同类,在那里你定义你的数据库表。如果你使用它,你可以引用像YourEntry.name_of_the_column这样的元素(你必须先导入这个类,例如:import .com.example. ...YourContract.YourEntry )。
这是一个contract class的例子。

import android.provider.BaseColumns;
public class YourContract {
    private YourContract(){}
    public static final class YourEntry implements BaseColumns {
        public static final String TABLE_NAME = "TABLE_TWHERETOGOLIST";
        public static final String intWhereToGoListOID = BaseColumns.intWhereToGoListOID;
        public static final String COL2 = "COL2";
        public static final String intCategoriesOID = "CategoriesOID ";