Deleting data in the database

The MicroJobs application enables the user to delete a job as well as create and change it. From the main application interface, the user clicks on the List Jobs button to get a list of jobs, and then clicks on a particular job to see the job detail. At this level, the user can click on the "Delete this job" menu item to delete the job. The application asks the user if he really wants to delete the job. When the user hits the "Delete" button in response, the following line of code in the MicroJobsDetail.java file is executed: db.deleteJob(job_id);

This code calls the deleteJob method of the MicroJobsDatabase class, passing it the job ID to delete. The code is similar to the functions we've already seen and lacks the same real-world features.

Example 8-5 shows you how to use the delete method.

Example 8-5. Using the delete method /**

* Delete a job from the database.

public void deleteJob(long job_id) {

String[] whereArgs = new String[]{Long.toString(job_id)}; try{

getWritableDatabase().delete("jobs", "_id=?", whereArgs); } catch (SQLException e) {

Log.e("Error deleteing job", e.toString());

Example 8-6 shows you how to use the execSQL method.

Example 8-6. Using the execSQL method /**

* Delete a job from the database.

public void deleteJob(long job_id) { String sql = String.format(

"DELETE FROM jobs " + "WHERE _id = '%d' ", job_id);

try{

getWritableDatabase().execSQL(sql); } catch (SQLException e) {

Log.e("Error deleteing job", e.toString());

0 0

Post a comment