如何从数据库中删除项目

时间:2015-07-27 13:59:18

标签: java android database 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);




    }
}

1 个答案:

答案 0 :(得分:1)

好吧,既然你有一个与数据库中每个条目相关联的唯一ID,你可以根据它删除,如下所示:

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

然后,当ListView中的某个项目被长按时,您可以调用该方法将其从数据库中删除,然后在remove(Object)上调用Adapter(或{ remove(int) List使用Adapter上的notifyDataSetChanged(),然后是ListView,以确保正确更新显示。

编辑:要回答有关如何将长按一下聆听者应用于Adapter中的项目的问题,这取决于您实施{{1}的方式}。如果它是自定义适配器,您只需将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; } });

Edit 2:

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; } 使用自定义适配器

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

import Foundation

extension NSDate{
var stringValue: String{
    return self.toString()
}

func toString() -> String {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MMM-dd"
    let str = formatter.stringFromDate(self)
    return str
}
}

extension String{
var dateValue: NSDate?{
    return self.toDate()
}

func toDate() -> NSDate? {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MMM-dd"
    if let date = formatter.dateFromString(self) {
        return date
    }else{
        // if format failed, Put some code here
        return nil // an example
    }
}
}

extension NSDate{
var starttimestringValue: String{
    return self.tostarttimeString()
}

func tostarttimeString() -> String {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "HH:mm"
    let str = formatter.stringFromDate(self)
    return str
}
}

extension String{
var starttimedateValue: NSDate?{
    return self.tostarttimeDate()
}

func tostarttimeDate() -> NSDate? {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "HH:mm"
    if let date = formatter.dateFromString(self) {
        return date
    }else{
        // if format failed, Put some code here
        return nil // an example
    }
}
}

extension NSDate{
var endtimestringValue: String{
    return self.toendtimeString()
}

func toendtimeString() -> String {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "HH:mm"
    let endstr = formatter.stringFromDate(self)
    return endstr
}
}

extension String{
var endtimedateValue: NSDate?{
    return self.toendtimeDate()
}

func toendtimeDate() -> NSDate? {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "HH:mm"
    if let date = formatter.dateFromString(self) {
        return date
    }else{
        // if format failed, Put some code here
        return nil // an example
    }
}
}
相关问题