Android DataServices – SQLite

You’ve made your way through the Android ‘Notepad‘ tutorial, but find yourself wanting more?  Maybe you want to deal with Typed Objects instead of all of these strings everywhere? While this code isn’t generic enough to paste into your app and use as-is, it is simple enough to adapt to your own typed objects.  Using the Interface described here makes it super easy to change the way you are storing your data, without having to refactor your app itself (imagine a hybrid online/offline storage, or as we’ll see in the next post, an Object Oriented DataBase[OODB]).

If you’d like to follow along in eclipse, source code is found here: http://svn.hat6.com/hat6public/DataServiceExample/trunk.

We’re only looking at one file here, ReminderSQLiteImpl.java. I’ve tried to make certain that the comments explain everything, so I’m just dumping the code below. This class comes in at about twice the size of the Notebook’s DBAdapter class, but most of that comes from my class storing more columns of data.

/**... imports removed ...**/
public class ReminderSQLiteImpl implements IReminderDataService {
	/**
	 * Static variables describing our schema.  We use these variables so that we can refer to the
	 * constants instead of having to worry about refactoring when our schema changes.
	 */
	public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_ICON = "icon";
    public static final String KEY_STARTDATE = "startDate";
    public static final String KEY_ENDDATE = "endDate";
    public static final String KEY_MODIFIED = "modified";
    //TAG for logging.
    private static final String TAG = "ReminderSQLiteImpl";
    /**
     * Static variables holding information about our database itself.
     * NAME and TABLE are self explanatory.
     * VERSION allows our app to know if it has to perform any upgrades (right now it's
     * 		simply dropping the entire table and all associated data).
     * CREATE allows us to specify the SQL needed to create our DB.
     */
    private static final String DATABASE_NAME = "hatsixExamples";
    private static final String DATABASE_TABLE = "remindersDS";
    private static final int    DATABASE_VERSION = 1;
    private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER primary key autoincrement, "
                + KEY_TITLE + " TEXT not null, "
                + KEY_STARTDATE + " TEXT, "
                + KEY_ENDDATE + " TEXT, "
                + KEY_MODIFIED + " DATE not null"
                + ");";

	/**
	 * Context is needed when interacting with the DB
	 */
	private final Context mCtx;
	/**
	 * DatabaseHelper is a private class, defined at the end of this file.
	 */
    private DatabaseHelper mDbHelper;
    /**
     * The actual Database.
     */
    private SQLiteDatabase mDb;

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public ReminderSQLiteImpl(Context ctx) {
		mCtx = ctx;
		open();
	}

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public ReminderSQLiteImpl open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    /**
     * Create a new reminder record.  We pass in a Reminder, rather than just
     * some text values like in the Notepad Example. If the reminder is
     * successfully created return the new rowId for that reminder, otherwise return
     * a -1 to indicate failure.
     *
     * @param r the Reminder we want saved.
     * @return rowId or -1 if failed
     */
    public long createReminder(Reminder r) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, r.getTitle());
        initialValues.put(KEY_STARTDATE, r.getStart());
        initialValues.put(KEY_ENDDATE, r.getEnd());
        initialValues.put(KEY_MODIFIED,convertDateToString(new Date()));

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Fetch all Reminders.  This will utilize SQLite's cursors and create an ArrayList
     * that is passed back to the caller.
     *
     * @return List of Reminders
     */
    public List<Reminder> fetchAllReminders(){
    	Cursor cursor = fetchAllRemindersCursor();
        int idColumn = cursor.getColumnIndex(KEY_ROWID);
        int titleColumn = cursor.getColumnIndex(KEY_TITLE);
        int startColumn = cursor.getColumnIndex(KEY_STARTDATE);
        int endColumn = cursor.getColumnIndex(KEY_ENDDATE);

        List<Reminder> list = new ArrayList<Reminder>();
    	if(cursor != null){
            if(cursor.moveToFirst()){

                int count = cursor.getCount();
                Log.d("ReminderSqliteImpl", "there are " + count + " records.");

                for(int i=0; i<count; i++){
                    Reminder reminder = new Reminder();
                    reminder.setId(cursor.getLong(idColumn));
                    reminder.setTitle(cursor.getString(titleColumn));
                    reminder.setStart(cursor.getString(startColumn));
                    reminder.setEnd(cursor.getString(endColumn));

                    list.add(reminder);

                    cursor.moveToNext();
                }
            }
        }
    	return list;
    }
    /**
     * Fetch Individual Reminder.  We take the 'query by example' approach, where we pass in
     * a Reminder.  This would allow us to query by Title if id wasn't set.
     *
     * @param r Reminder with id set to the Reminder we want fetched.
     * @return Reminder that was passed in, with data filled out from query.
     */
    public Reminder fetchReminder(Reminder r){
    	Cursor cursor = fetchReminderCursor(r.getId());
        int idColumn = cursor.getColumnIndex(KEY_ROWID);
        int titleColumn = cursor.getColumnIndex(KEY_TITLE);
        int startColumn = cursor.getColumnIndex(KEY_STARTDATE);
        int endColumn = cursor.getColumnIndex(KEY_ENDDATE);
    	if(cursor != null){
            r.setId(cursor.getLong(idColumn));
            r.setTitle(cursor.getString(titleColumn));
            r.setStart(cursor.getString(startColumn));
            r.setEnd(cursor.getString(endColumn));
    	}
    	return r;
    }
    /**
     * Update the reminder using the details provided. We pass in a
     * Reminder, create ContentValues from that Reminder, then update
     * the record based on rowID
     *
     * @param r the Reminder to update
     * @return true if the reminder was successfully updated, false otherwise
     */
    public boolean updateReminder(Reminder r) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, r.getTitle());
        args.put(KEY_STARTDATE, r.getStart());
        args.put(KEY_ENDDATE, r.getEnd());
        args.put(KEY_MODIFIED,convertDateToString(new Date()));

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + r.getId(), null) > 0;
    }

    /**
     * Delete the reminder.  Rather than passing in the rowID, we pass the entire
     * reminder.  Again, by passing objects, our app is significantly simplified.
     *
     * @param r the Reminder to be deleted.
     * @return true if deleted, false otherwise
     */
    public boolean deleteReminder(Reminder r) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + r.getId(), null) > 0;
    }

    /**
     * Return a Cursor over the list of all reminders in the database.
     * This is more of a convenience function, as we don't allow outside
     * classes to use it anymore
     *
     * @return Cursor over all reminder
     */
    private Cursor fetchAllRemindersCursor() {

        return mDb.query(DATABASE_TABLE, new String[] {
        			KEY_ROWID,
        			KEY_TITLE,
        			KEY_STARTDATE,
        			KEY_ENDDATE,
        			KEY_MODIFIED
        			}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the reminder that matches the given rowId
     * Again, a convenience function, as we don't allow outside classes ot use it
     *
     * @param rowId id of reminder to retrieve
     * @return Cursor positioned to matching reminder, if found
     * @throws SQLException if reminder could not be found/retrieved
     */
    private Cursor fetchReminderCursor(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[] {
            			KEY_ROWID,
            			KEY_TITLE,
            			KEY_STARTDATE,
            			KEY_ENDDATE,
            			KEY_MODIFIED
            			}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * convertStringToDate will take a Sqlite String and convert it to a date
     * @param s String to convert to Date
     * @return Date object
     */
	private Date convertStringToDate(String s){
		Date date = null;
		DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = iso8601Format.parse(s);
		} catch (ParseException e) {
			Log.e("Reminder.convertStringToDate", "Parsing ISO8601 datetime failed", e);
		}
		return date;
	}

	/**
	 * convertDateToString will take a Date object and return a SQLite date string
	 * @param date Date
	 * @return String
	 */
	private String convertDateToString(Date date){
		long when = date.getTime();
		int flags = 0;
		flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
		flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
		flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
		flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

		String finalDateTime = android.text.format.DateUtils.formatDateTime(mCtx,
				when + TimeZone.getDefault().getOffset(when), flags);

		return finalDateTime;

	}

    /**
     * DatabaseHelper basically copied from Androids NotebookExample.
     * Here we short-circuit some functions to make our above code
     * more readable.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
            onCreate(db);
        }
    }

}

2 comments ↓

#1 Android DataServices – DB4O — h6 – HatSix on 12.05.09 at 8:06 pm

[...] ← Android DataServices – SQLite [...]

#2 Android DataServices — h6 – HatSix on 12.05.09 at 8:42 pm

[...] Android DataServices – SQLite → [...]

viagra
generic viagra overnight delivery
generic viagra manila
buy levitra on line
buy generic online pill zoloft
original studies on viagra
generic viagra overnight shipping
order altace
discount glucophage
online viagra sale
viagra 100
buy evista generic
buy nolvadex without prescription
generic arava
buy cheap nexium india
online ritalin viagra paypal
buy cheap viagra online
buy viagra cialis
buy ultram now
discout cialis
order viagra viagra online
buy viagra on line
buy low cost zocor
order pravachol
generic viagra 100mg soft pills
generics cialis
buy viagra pill online
buy levitra
generic for viagra
buy kamagra glasgow
buy levitra us
cialis 20mg
buy altace low cost
cheapest silagra
purchase viagra online
generic viagra on line
pill ultram
over the counter drug to viagra
buy cheap levitra
order zithromax
cheap viagra new zealand
viagra 6 free sample
online pill viagra
pill diflucan
order hoodia online
buy lipitor online
buy online ultram
genaric plavix
buy cialis online pharmacy
buy cheap side effects altace
order viagra buying viagr
generic viagra overnigh
purchase generic viagra online
cheap generic 50 mg viagra
cheap generic levitra without prescription
order viagra air travel php
buy cialis online uk
buy canada in propecia
buy canada online zyban
buy online viagra
buy cheap imitrex online
online prescription for viagra
cialis generic uk
buy cheap altace side effect
viagra cialias
generic viagra generique
buy lasix
herb viagra
generika silagra
cheap cialis for you
generica viagra
generic cialis viagra caverta buy online
generic brand viagra
generic viagra contains sildenafil citrate
order nolvadex
over the counter viagra substitutes
buy kamagra pound
purchase kamagra
buy pill viagra
generic toronto viagra
buy cheap tramadol online tramadol
generic viagra drugstore india
cheapest prilosec
buy viagra online uk
cialis 10
cheap viagra online at
buy cheap evista
fda cipro
generic viagra caverta
viagra 35008
buy depakote
buy discount valium
order ultram
buy cheap generic zyban
buy pravachol
viagra 13-13-13
otros viagra y
generic viagra work
buy cheap celebrex
discount celebrex
purchase nexium
buy cheap kamagra online uk
cialis generic online
buy cialis fioricet
online perscriptions for viagra
generic viagra for under $50.00
buy generic norvasc
buy generic zithromax online
online viagra canada
cheap genric viagra online
levitra 20
cheapest allegra
cheap free shipping soma
buy viagra online buy
cialis 2005
fda avandia
buy cheap diflucan online
cheapest zantac
buy viagra canada warning
cheap prevacid
overseas generic viagra
buy zyprexa
buy altace
generic viagra 9 9 9 9
buy overseas viagra
generic viagra forumes
buy cialis canada
buy viagra online au
buy cialis dream online pharmaceutical
online viagra consultation
buy order flomax
discount actos
buy online zantac
generic viagra free pills worldwide
buy fosamax 70mg
generic shop viagra
buy cheap zithromax
discount altace
cheap altace no prescription
buy viagra or levitra
buy diflucan where
cheap fosamax
buy viagra 1
generic viagra nz
cheap neurontin
order discount viagra
online consultation viagra
order viagra uk
generic viagra meltabs
buy retin-a no perscription
cheap nolvadex
buy zocor
order viagra overnight delivery
buy allegra without prescription
generic neurontin
cheap lily lcos cialis
generic amoxil
buy crestor
buy discount diflucan online
other thigns besides viagra
generic viagra when
nolvadex buy
buy generic online viagra
generic prilosec
cheap canadian cialis online
buy discount levitra online
buy protonix
buy viagra online 35008
buy kamagra uk
discount flomax
cheap viagra in uk
order cipro
cheap viagra without a pr
generic viagra rating
order zoloft online without prescription
buspar drug
buy ultram 32
online uk viagra
generic viagra woman
buy effexor xr side effects
overnight zyrtec
order ultram with no prescription
buy somas oline
buy generic propecia
cheap somas
cheap viagra overnight delivery
generic viagra buy sildenafil citrate
buy drug generic hyzaar india
buy generic viagra
discount pravachol
buy kamagra the
overdose viagra
buy cheap generic cialis
generic viagra in australia
buy tamiflu online
generic viagra india review
generic viagra cheapest online
buy cialis softtabs information
order viagra international ships
buy pfizer viagra
cheap generic drugs caverta
buy cheap viagra viagra viagra
generic list new site viagra
over sea generic viagra
fda lipitor
generic viagra india trial pack
cheap viagra from mexico
buy lasix without prescription
online pharmacy prescription drug viagra
viagra american express
buy cheapest viagra online
buy discount viagra viagra viagra
buy cialis huge discounts online
buy cialis cheap us
buy cheapest propecia
generic viagra drugs brand order pill
buying soma online without a prescription
buy viagra discrete uk
buy diet hoodia online pill
cialis generic canada
cheapest flomax
generic risk using viagra
online us pharmacies generic viagra softtabs
buy viagra with paypal
generic viagra pill
cialis generic levitra viagra
buy levitra day trippers
cialis generic name
generic viagra from india
buy cheap ultram
buy generic allegra
buy cialis online now
generic viagra caverta veega generic viagra
buy online singulair
buy nolvadex on line
over night viagra
buy generic imitrex
fda cialis
buy cheap online propecia
buy cheapest cialis
buy namebrand ultram
buy cialis grand rapids michigan
buy cialis no online prescription
order diflucan
order zyprexa
purchase viagra on line
order cialis
buy viagra inte
generic viagra and online pharmacies
buy diflucan 100 mg prescription
generic viagra 100mg
order status viagra
generic zocor
online viagra australia
viagra 100 pic
buy cialis online dream pharmaceutical
generic viagra deals
buy cialis pills generic
generic viagra buy viagra online viagra
buy cheap valium
cheapest kamagra
buy imitrex oral
buy discounted viagra
purchase viagra in australia
generic viagra in british columbia
buy lexapro medication online
buy genwtic zyban
pic prilosec
order viagra on-line
cheap kamagra
buy levitra international pharmacy
buy viagra safeway pharmacy
buy cheap online viagra viagra
buy cheap effexor xr
buy cialis soft
generica cialis
buy amaryl
generic n plainfield viagra
cheapest norvasc
order viagra 1
generic viagra accepts american express
buy kamagra tablets
buy viagra uk
buy line soma
cheaper viagra
buy generic celebrex
buy viagra zenegra
buy free imitrex shipping
generic sample pacs of viagra
cialis generic overnight shipping
overnight generic viagra american express
generics levitra
discount kamagra
generic viagra 24 hours
purchase viagra professional
buy imitrex where
viagra 50mg
buy cash delivery soma
buy cheap generic prilosec
drug cialis
cialis generic softtabs
buy discount lipitor
buy cialis online overnight
buy viagra from britain
buy generic soma without prescription
order zovirax online rx pharmaceutical
buy viagra all information
pill propecia
buy viagra generic
fda levitra
cialis generic soft
purchasing viagra online for cheap
buy generic xenical
buy viagra securely online
online viagra prescription canada
cheap generic nolvadex online order
buy cialis online say wordpress
generic line viagra
generic tamiflu
cheap valium
buy diflucan 150 mg
generic viagra from canada
discount on cialis
buy buy prilosec online
cheap gen viagra bi
buy sublingual cialis online
buy discount evista
online uk viagra sales
cheap ultram
buying soma without a prescription
cialis generic on line
buy viagra online canada
buy online zocor
overdose claritin
online pharmacy propecia viagra
geneic viagra
buy neurontin online
generic viagra mg blue pill
pill viagra
purchase cozaar
buy cialis online cheap
buy kamagra
generic cialis and viagra
viagra 25
generic viagra melt tabs
buy cheap online prescription viagra
generic diovan
generic viagra and pay pal
generic altace
viagra 50mg sverige
buy drug satellite tv levitra
generic avandia
viagra 2bonline
generic name for viagra
buy norvasc no prescription
buy nexium
buy silagra
order ultram without a prescription
genaric lipitor
buy norvasc low cost
buy generic online prilosec
buy discount diflucan free shipping
generic viagra 100 mg
generic viagra lowest prices
order buspar
buy drug zyrtec
generic soma
generic viagra does it work
order viagra with my checking account
generic viagra and generic drug
order flomax
generi allegra
cheap viagra soft tablet
cialis generic discount
buy cheap side effects zantac
viagra 2 day delivery
buy cialis dreampharmaceuticals online
viagra 24 hours delivary
discount cozaar
generic viagra master card purchase
online order viagra viagra
order zyban online dream pharmaceutical
buy cheap claritin
buy cialis money order
buy cheap tramadol online 35009
buy evista
discount cialis fedex
buy viagra soft online
purchase tamiflu
fda celebrex
online viagra order
buy levitra online viagra
buy cialis soft online
buy deal herbal viagra viagra
generic viagra purchase
buy viagra canada review
buy clomid
fda lasix
buy evista discount
purchase claritin
buy generic viagra usa
cheapest nolvadex
buy cheap kamagra uk
buy amlip amlodipine norvasc
cheapest lasix
buy generic cipro overnight
buy lexapro in canada
discount protonix
cheap norvasc
buy allegra zyrtec online
buy generic retin-a fedex
buy cialis toronto
generic viagra no prescription
online prescription scams viagra
generick viagra
buy free viagra on internet
buy lexapro
cheapest xenical
online generic viagra
generic singulair
cheap viagra in the uk
buy viagra in australia
discount crestor
buy levitra lowest prices
cheap altace online cheap
buy kamagra canada
overdose of viagra
nolvadex and
buy claritin
cheapest lotensin
buy soma
overnight cheap viagra
buy cialis generic pharmacy online
generic propecia
buy viagra online canadian
generic viagra online generic viagra online
online viagra pharmacy
cialis generic pharmacy online
buy cheap cialis
cialis generic safety
generic viagra mexico
generic viagra in united state
buy singulair
buy from pharmacy us viagra
buy lexapro cheap ndice
cheapest glucophage
order aciphex
generic overnight shipping viagra
order generic viagra
cheap generic viagra no script
generic viagra by fedx
over the counter viagra
buy viagra alternative
online zantac
order nexium
generic viagra no prescriptio
cialis generic cheap
generic meltabs viagra php
buy cheap generic viagra
generic softtabs viagra
buy viagra in amsterdam
retin-a .1
order viagra now money
philippines viagra
overnight canadian viagra
buy generic soma online
buy viagra softtabs
generic flomax
buy discount viagra
cialis generic impotence kamagra viagra viagra
buy generic online zyrtec
buy atarax
cheapest viagra
cheap flomax buy online
cheap viagra fast shipping
buy levitra medication
cheap generic levitra from mexico
buy internet viagra
buy conjugated linoleic acid cla
buy cialis online from canada
discount propecia
discount diflucan
cheap protonix
online viagra increase fertility sildenafil citrat
cheap viagra online prescription
online diflucan
buy online cialis
online pharmacy uk viagra
discount cialis uk
generic names for viagra
buy valium online
purchase viagra
buy tramadol ultram
buy cheap silagra