Alex
Alex

Reputation: 35

How to delete items from a database

I am making an app that stores a name and a mark in a database and it displays this in a listview. How can I delete an item of the listview and also of the database with a long press of the item in the listview??

Here is the code of the database helper:

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




    }
}

Upvotes: 2

Views: 290

Answers (1)

Cruceo
Cruceo

Reputation: 6834

Well, since you have a unique ID associated with each entry in your database, you could delete based on that, like so:

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

Then, when an item in your ListView is long-pressed, you could call that method to remove it from your database, and then call remove(Object) on your Adapter (or remove(int) on the List your Adapter uses), followed by notifyDataSetChanged() to ensure it updates the display correctly.

Edit: To answer your question about how to apply a long click listener to an item in your ListView, it depends on how you've implemented the Adapter. If it's's a custom adapter, you can simply set an onLongClickListener() to your root View (e.g. convertView). If you're not using that, you can try attaching an AdapterView.OnItemLongClickListener like this to your 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: Using a custom Adapter

In your getView() method, add the following before returning 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;
}

Upvotes: 1

Related Questions