Adding Updating and Removing Rows

The SQLiteDatabase class exposes insert, delete, and update methods that encapsulate the SQL statements required to perform these actions. Additionally, the execSQL method lets you execute any valid SQL on your database tables should you want to execute these (or any other) operations manually.

Any time you modify the underlying database values, you should call refreshQuery on each Cursor that has a view on the affected table.

Inserting New Rows

To create a new row, construct a ContentValues object and use its put methods to provide a value for each column. Insert the new row by passing the Content Values object into the insert method called on the target database — along with the table name — as shown in Listing 7-6.

LISTING 7-6: Inserting new rows into a database

Wrox.com

Available for download on // Create a new row of values to insert.

ContentValues newValues = new ContentValues();

// Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ]

// Insert the row into your table myDatabase.insert(DATABASE_TABLE, null, newValues);

Updating a Row

Updating rows is also done with Content Values.

Create a new ContentValues object, using the put methods to assign new values to each column you want to update. Call update on the database, passing in the table name, the updated Content Values object, and a where clause that specifies the row(s) to update as shown in Listing 7-7.

LISTING 7-7: Updating a database row Available for download on // Define the updated row content. Wrax.com ContentValues updatedValues = new ContentValues()

// Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ]

// Update the row with the specified index with the new values. myDatabase.update(DATABASE_TABLE, newValues, where, null);

Deleting Rows

To delete a row simply call delete on a database, specifying the table name and a where clause that returns the rows you want to delete as shown in Listing 7-8.

LISTING 7-8: Deleting a database row

Available for download on myDatabase.delete(DATABASE_TABLE, KEY_ID + " = " + rowId, null); Wrax.com

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment