java - 如何从数据库中删除项目

标签 java android database listview

我正在制作一个在数据库中存储名称和标记的应用程序,并将其显示在 ListView 中。如何通过长按 ListView 中的项目来删除 ListView 以及数据库中的项目?

这是数据库助手的代码:

public class PersonDatabaseHelper {

    private static final String TAG = PersonDatabaseHelper.class.getSimpleName();

    // database configuration
    // if you want the onUpgrade to run then change the database_version
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "mydatabase.db";

    public static String query;

    // table configuration
    private static final String TABLE_NAME = "person_table";         // Table name
    private static final String PERSON_TABLE_COLUMN_ID = "_id";     // a column named "_id" is required for cursor
    private static final String PERSON_TABLE_COLUMN_NAME = "person_name";
    private static final String PERSON_TABLE_COLUMN_PIN = "person_pin";

    private DatabaseOpenHelper openHelper;
    private SQLiteDatabase database;

    // this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
    // but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
    public PersonDatabaseHelper(Context aContext) {

        openHelper = new DatabaseOpenHelper(aContext);
        database = openHelper.getWritableDatabase();
    }

    public void insertData (String aPersonName, String aPersonPin) {

        // we are using ContentValues to avoid sql format errors

        ContentValues contentValues = new ContentValues();

        contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
        contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);

        database.insert(TABLE_NAME, null, contentValues);
    }

    public Cursor getAllData () {

        String buildSQL = "SELECT * FROM " + TABLE_NAME;

        Log.d(TAG, "getAllData SQL: " + buildSQL);

        return database.rawQuery(buildSQL, null);
    }

    // this DatabaseOpenHelper class will actually be used to perform database related operation

    private class DatabaseOpenHelper extends SQLiteOpenHelper {

        public DatabaseOpenHelper(Context aContext) {
            super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            // Create your tables here

            String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_TABLE_COLUMN_NAME + " TEXT, " + PERSON_TABLE_COLUMN_PIN + " TEXT )";

            Log.d(TAG, "onCreate SQL: " + buildSQL);

            sqLiteDatabase.execSQL(buildSQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
            // Database schema upgrade code goes here

            String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;

            Log.d(TAG, "onUpgrade SQL: " + buildSQL);

            sqLiteDatabase.execSQL(buildSQL);       // drop previous table

            onCreate(sqLiteDatabase);               // create the table from the beginning
        }
    }

    public void average() {
        String query = "SELECT AVG("+PERSON_TABLE_COLUMN_PIN +") FROM "+TABLE_NAME;
        database.rawQuery(query, null);




    }
}

最佳答案

好吧,因为你有一个唯一的 ID 与你的数据库中的每个条目相关联,你可以基于它进行删除,如下所示:

public void deleteItem(int itemId){
    this.getWritableDatabase().delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + itemId, null);
}

然后,当您的 ListView 中的项目被长按时,您可以调用该方法将其从数据库中删除,然后调用 remove(Object)您的适配器(或您的适配器使用的列表上的remove(int)),然后是notifyDataSetChanged () 以确保它正确地更新显示。

编辑:要回答有关如何将长按监听器应用于 ListView 中的项目的问题,这取决于您如何实现 适配器。如果它是自定义适配器,您只需将 onLongClickListener() 设置为您的根 View(例如 convertView)。如果您没有使用它,您可以尝试将这样的 AdapterView.OnItemLongClickListener 附加到您的 ListView:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long arg3) {
        // get the data from your list at position, i.e. data.get(position)
        // then pass that object / id to your database helper, e.g.

        Person p = data.get(position);
        personDatabaseHelper.deleteItem(p.getId());

        data.remove(position); // or adapter.remove(p), depends on your implementation
        adapter.notifyDataSetChanged(); // remove the object from your Adapter and notify it of the change

        return true;
    }
});

编辑 2: 使用自定义适配器

在您的 getView() 方法中,在返回 convertView 之前添加以下内容:

public View getView(final int position, View convertView, ViewGroup parent){

    // your other stuff here

    convertView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Person p = getItem(position);

            personDatabaseHelper.deleteItem(p.getId());  
            remove(p);

            notifyDataSetChanged(); 
            return true;
        }
    });

    return convertView;
}

关于java - 如何从数据库中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655167/

相关文章:

从 OS X 到 Windows 的 Java 编码

java - Active Directory 允许使用禁用的帐户创建 InitialContext

android - 自定义 TabWidget Android 选项卡指示器

Android:如何从 gridview 中删除一个项目,让剩余的项目洗牌到位

java - 从 double 到 float 的可能有损转换

java - Android从末尾读取文本文件

android - 什么是 'action android:name="com.android.vending.INSTALL_REFERRER"'?

sql - 我应该如何对此进行单元测试

sql-server - 本地 SQL Server 数据库和 Azure SQL 数据库之间的两种方式同步

c# - Return value using String result=Command.ExecuteScalar() result返回null时出现错误