Listing 99 srccomcookbookdataMyDBjava


import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteException;

import android.util.Log;

public class MyDB {

private SQLiteDatabase db; private final Context context; private final MyDBhelper dbhelper; public MyDB(Context c){ context = c;

dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,


public void close() {

public void open() throws SQLiteException {

db = dbhelper.getWritableDatabase(); } catch(SQLiteException ex) {

Log.v("Open database exception caught", ex.getMessage()); db = dbhelper.getReadableDatabase();

public long insertdiary(String title, String content) {


ContentValues newTaskValue = new ContentValues(); newTaskValue.put(Constants.TITLE_NAME, title); newTaskValue.put(Constants.CONTENT_NAME, content); newTaskValue.put(Constants.DATE_NAME, java.lang.System.currentTimeMillis()); return db.insert(Constants.TABLE_NAME, null, newTaskValue); } catch(SQLiteException ex) {

Log.v("Insert into database exception caught", ex.getMessage()); return -1;

public Cursor getdiaries() {

Cursor c = db.query(Constants.TABLE_NAME, null, null, null, null, null, null);

return c;

The MyDBhelper class extends SQLiteOpenHelper and is shown in Listing 9.10.The SQLiteOpenHelper framework provides methods to manage database creation and upgrades. The database is initialized in the class constructor MyDBhelper() .This requires the context and database name to be specified for creation of the database file under /data/data/com.cookbook.datastorage/databases and database schema version to determine whether the onCreate() or onUpgrade() method is called.

Tables can be added in the onCreate() method using a custom SQL command such as:

create table MyTable (key_id integer primary key autoincrement, title text not null, content text not null, recorddate long);

Whenever a database needs to be upgraded (when a user downloads a new version of an application, for example), the change in database version number calls the onUpgrade() method. This can be used to alter or drop tables as needed to update the tables to the new schema.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment