Home | History | Annotate | Download | only in notepad2
      1 /*
      2  * Copyright (C) 2008 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
      5  * use this file except in compliance with the License. You may obtain a copy of
      6  * the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     13  * License for the specific language governing permissions and limitations under
     14  * the License.
     15  */
     16 
     17 package com.android.demo.notepad2;
     18 
     19 import android.content.ContentValues;
     20 import android.content.Context;
     21 import android.database.Cursor;
     22 import android.database.SQLException;
     23 import android.database.sqlite.SQLiteDatabase;
     24 import android.database.sqlite.SQLiteOpenHelper;
     25 import android.util.Log;
     26 
     27 /**
     28  * Simple notes database access helper class. Defines the basic CRUD operations
     29  * for the notepad example, and gives the ability to list all notes as well as
     30  * retrieve or modify a specific note.
     31  *
     32  * This has been improved from the first version of this tutorial through the
     33  * addition of better error handling and also using returning a Cursor instead
     34  * of using a collection of inner classes (which is less scalable and not
     35  * recommended).
     36  */
     37 public class NotesDbAdapter {
     38 
     39     public static final String KEY_TITLE = "title";
     40     public static final String KEY_BODY = "body";
     41     public static final String KEY_ROWID = "_id";
     42 
     43     private static final String TAG = "NotesDbAdapter";
     44     private DatabaseHelper mDbHelper;
     45     private SQLiteDatabase mDb;
     46 
     47     /**
     48      * Database creation sql statement
     49      */
     50     private static final String DATABASE_CREATE =
     51         "create table notes (_id integer primary key autoincrement, "
     52         + "title text not null, body text not null);";
     53 
     54     private static final String DATABASE_NAME = "data";
     55     private static final String DATABASE_TABLE = "notes";
     56     private static final int DATABASE_VERSION = 2;
     57 
     58     private final Context mCtx;
     59 
     60     private static class DatabaseHelper extends SQLiteOpenHelper {
     61 
     62         DatabaseHelper(Context context) {
     63             super(context, DATABASE_NAME, null, DATABASE_VERSION);
     64         }
     65 
     66         @Override
     67         public void onCreate(SQLiteDatabase db) {
     68 
     69             db.execSQL(DATABASE_CREATE);
     70         }
     71 
     72         @Override
     73         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     74             Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
     75                     + newVersion + ", which will destroy all old data");
     76             db.execSQL("DROP TABLE IF EXISTS notes");
     77             onCreate(db);
     78         }
     79     }
     80 
     81     /**
     82      * Constructor - takes the context to allow the database to be
     83      * opened/created
     84      *
     85      * @param ctx the Context within which to work
     86      */
     87     public NotesDbAdapter(Context ctx) {
     88         this.mCtx = ctx;
     89     }
     90 
     91     /**
     92      * Open the notes database. If it cannot be opened, try to create a new
     93      * instance of the database. If it cannot be created, throw an exception to
     94      * signal the failure
     95      *
     96      * @return this (self reference, allowing this to be chained in an
     97      *         initialization call)
     98      * @throws SQLException if the database could be neither opened or created
     99      */
    100     public NotesDbAdapter open() throws SQLException {
    101         mDbHelper = new DatabaseHelper(mCtx);
    102         mDb = mDbHelper.getWritableDatabase();
    103         return this;
    104     }
    105 
    106     public void close() {
    107         mDbHelper.close();
    108     }
    109 
    110 
    111     /**
    112      * Create a new note using the title and body provided. If the note is
    113      * successfully created return the new rowId for that note, otherwise return
    114      * a -1 to indicate failure.
    115      *
    116      * @param title the title of the note
    117      * @param body the body of the note
    118      * @return rowId or -1 if failed
    119      */
    120     public long createNote(String title, String body) {
    121         ContentValues initialValues = new ContentValues();
    122         initialValues.put(KEY_TITLE, title);
    123         initialValues.put(KEY_BODY, body);
    124 
    125         return mDb.insert(DATABASE_TABLE, null, initialValues);
    126     }
    127 
    128     /**
    129      * Delete the note with the given rowId
    130      *
    131      * @param rowId id of note to delete
    132      * @return true if deleted, false otherwise
    133      */
    134     public boolean deleteNote(long rowId) {
    135 
    136         return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    137     }
    138 
    139     /**
    140      * Return a Cursor over the list of all notes in the database
    141      *
    142      * @return Cursor over all notes
    143      */
    144     public Cursor fetchAllNotes() {
    145 
    146         return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
    147                 KEY_BODY}, null, null, null, null, null);
    148     }
    149 
    150     /**
    151      * Return a Cursor positioned at the note that matches the given rowId
    152      *
    153      * @param rowId id of note to retrieve
    154      * @return Cursor positioned to matching note, if found
    155      * @throws SQLException if note could not be found/retrieved
    156      */
    157     public Cursor fetchNote(long rowId) throws SQLException {
    158 
    159         Cursor mCursor =
    160 
    161             mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
    162                     KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
    163                     null, null, null, null);
    164         if (mCursor != null) {
    165             mCursor.moveToFirst();
    166         }
    167         return mCursor;
    168 
    169     }
    170 
    171     /**
    172      * Update the note using the details provided. The note to be updated is
    173      * specified using the rowId, and it is altered to use the title and body
    174      * values passed in
    175      *
    176      * @param rowId id of note to update
    177      * @param title value to set note title to
    178      * @param body value to set note body to
    179      * @return true if the note was successfully updated, false otherwise
    180      */
    181     public boolean updateNote(long rowId, String title, String body) {
    182         ContentValues args = new ContentValues();
    183         args.put(KEY_TITLE, title);
    184         args.put(KEY_BODY, body);
    185 
    186         return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    187     }
    188 }
    189