繁体   English   中英

Android,删除列表和sqllite java中的项目

[英]Android, delete item in list and in sqllite java

问题末尾的注意是更新但仍然不起作用

大家好,我有一个列表和一个弹出窗口,我可以在其中单击delete

如何删除我在列表中长按的项目
此列表存储在本地 sqllite 数据库中。

我想点击删除删除爱丁堡项目

在此处输入图片说明

我的列表代码:

public class ViewListContents extends AppCompatActivity {

    DatabaseHelper myDB;

    @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<String> 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();
        }

    }

}

这是我的数据库代码:

    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,
                null
        );
    }


}

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

更新 1.0:

我现在遇到的问题是,我不知道如何获取我长按的 ListView 项的 ID,然后在出现的弹出窗口上按删除。

我必须将这个 ListView 项目的(ID 无论如何)添加到我的数据库代码中才能删除这个项目。

如果您有问题,请提问。

请详细描述:) 我不知道我该怎么做

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

这应该是读取元素的函数:
(检查这个更多,它可能对您有用)

更新:适应您正在使用的合同类

    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 ";
        /*Other columns*/
    }
}

(因此您必须更改您的 onCreate 以使用 YourEntry.collum 或 YourEntry.TABLE_NAME,例如上面链接中的示例)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM