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 → [...]

buy viagra online prescription group buy viagra online u buy viagra online uk buy viagra online web meds buy viagra online without prescription buy viagra onlines buy viagra or cilas buy viagra order viagra buy viagra other drug online buy viagra over the counter buy viagra over the counter us buy viagra overnight buy viagra per pill buy viagra pharmacy online buy viagra pill buy viagra pill online buy viagra pills buy viagra porno at maygreat org buy viagra powered by phpbb buy viagra prescription buy viagra prescription america buy viagra prescription america carisoprodol buy viagra prescription online buy viagra price drugs on buy viagra removethis buy viagra s diary buy viagra s journal buy viagra safeway pharmacy buy viagra sale buy viagra securely online buy viagra soft tabs buy viagra softtabs buy viagra the best quality pills buy viagra toronto buy viagra uk buy viagra ups buy viagra us pharmacy low prices buy viagra vaniqa prescription buy viagra viagra buy viagra viagra online buy viagra where buy viagra with discount buy viagra with paypal buy viagra without a perscription buy viagra without a prescription buy viagra without prescription buy viagra without prescription online pharmacy buy viagra without prescription pharmacy online buy viagra woman buy viagra xanax buy viagra zenegra cheap canadian viagra cheap cheap deal pill viagra viagra cheap cheap discount sale viagra cheap cheap herbal viagra viagra viagra cheap cheap viagra cheap cheap viagra viagra cheap cialis viagra cheap citrate generic sildenafil viagra cheap deal deal pill viagra cheap deal discount price viagra cheap deal discount viagra viagra cheap deal viagra cheap drug generic generic viagra cheap drug online prescription viagra cheap drug retin viagra wellbutrin cheap drug viagra cheap drugs viagra cialas cheap followup post viagra cheap foreign generic viagra cheap free price viagra cheap free viagra cheap free viagra viagra cheap gen viagra bi cheap genaric viagra kamagra cheap generic 50 mg viagra cheap generic drugs viagra cialis levitra cheap generic india viagra cheap generic kamagra kamagra uk viagra cheap generic online viagra cheap generic overnight viagra cheap generic pill ultram ultram viagra cheap generic substitute viagra cheap generic viagra cheap generic viagra 1.00 cheap generic viagra co uk cheap generic viagra from usa cheap generic viagra no prescription cheap generic viagra no script cheap generic viagra online cheap generic viagra overnight delivery cheap generic viagra substitute cheap generic viagra substitutes cheap generic viagra uk cheap herbal sale viagra viagra cheap herbal sale viagra viagra viagra cheap herbal viagra cheap herbal viagra viagra cheap herbal viagra viagra viagra cheap india viagra cheap inexpensive viagra cheap kamagra uk viagra cheap kamagra viagra cheap man viagra cheap meltabs online viagra cheap meltabs viagra cheap mexico viagra cheap molde ticket viagra cheap no prescription viagra cheap online generic viagra cheap online order viagra cheap online pharmacy viagra viagra cheap online pill price viagra viagra cheap online pill viagra cheap online price price viagra cheap online purchase viagra cheap online sales viagra cheap online softtabs viagra cheap online viagra cheap online viagra viagra cheap online viagra viagra viagra cheap order prescription viagra cheap order site viagra cheap overnight viagra cheap pfizer viagra cheap pharmaceutical viagra cheap pharmacy viagra cheap pharmacy viagra cialis levitra cheap phizer viagra cheap pill pill sale viagra cheap pill viagra cheap prescription viagra cheap prescription viagra without cheap price viagra cheap quality viagra cheap referrers total viagra cheap sale viagra cheap site viagra cheap soft tab viagra cheap soft viagra cheap source viagra cheap uk viagra cheap viagra cheap viagra 25mg cheap viagra ambien generic cananda order viagra with my checking account order viagra without a prescription order viagra without prescription cheap viagra at online pharmacy cheap viagra bi cheap viagra buy pharmacy online now cheap viagra canada cheap viagra cialis cheap viagra cialis india cheap viagra direct cheap viagra discount cheap viagra discount viagra buy viagra cheap viagra fast shipping cheap viagra from pfizer cheap viagra generic cheap viagra generic paypal cheap viagra in the uk cheap viagra in uk cheap viagra india cheap viagra kamagra cheap viagra new zealand cheap viagra no prescription cheap viagra no presrciption 50mg cheap viagra nz cheap viagra online cheap viagra online a href cheap viagra online order viagra now cheap viagra online pharmacy online cheap viagra online prescription cheap viagra online uk cheap viagra uk cheap viagra uks viagra and coupon cialis 20 cialis 10mg cialis 10 cialis blindness cheap viagra viagra cheap viagra without a prescription cheap viagra without prescription cheap websites for viagra cheaper cialis levitra viagra cheaper viagra cialis 20mg cialis 24 cialis 30 cialis 30mg cialis 32 cialis 5 cialis 50mg cialis 5mg cialis 1 cheapest online viagra cheapest place buy viagra online cheapest place to buy viagra cheapest place to buy viagra online cheapest prescription viagra cheapest price for generic viagra cheapest price for viagra cheapest price on viagra cheapest price viagra cheapest prices for viagra online cheapest prices on generic viagra cheapest uk supplier viagra cheapest uk viagra cheapest viagra cheapest viagra and regalis cheapest viagra anywhere cheapest viagra cheapest generic viagra home cheapest brand viagra cheapest cheap viagra cheapest generic price viagra cheapest generic silagra viagra cheapest generic substitute viagra cheapest generic viagra cheapest generic viagra and canada cheapest generic viagra and cialis cheapest generic viagra and cialis pills cheapest generic viagra sent overnight cheapest in uk viagra cheapest line viagra cheapest viagra generic substitute cheapest viagra homepage cheapest viagra in the uk viagra cailis viagra canada prescription viagra canada price viagra canada satisfaction guarantee viagra canadaian prices viagra canadian viagra canadian prescriptions viagra canadian price shipped buy and purchase viagra online buy australian viagra buy buy cheap medved viagra buy buy cheap viagra buy buy medved viagra viagra buy buy online sale viagra viagra buy buy online viagra viagra buy buy sale viagra viagra buy buying sale viagra buy cailis viagra singapore buy can reply viagra buy canada in viagra buy canada viagra buy cheao cgeap kamagra uk viagra buy cheap cheap kamagra uk viagra buy cheap deal pill viagra cheapest viagra in uk cheapest viagra in uk che cheapest viagra in uk cheap cheapest viagra on line cheapest viagra on the internet cheapest viagra on the net cheapest viagra online cheapest viagra online in the uk cheapest viagra online pharmacy cheapest viagra online plus zenegra cheapest viagra overnight cheapest viagra price cheapest viagra prices cheapest viagra prices uk cheapest viagra substitut viagra calgary viagra calias viagra can viagra canada viagra canada generic viagra canada online viagra canada online pharmacy viagra canada pharmacy discount viagra drug discount viagra europe discount viagra generic discount viagra in the usa discount viagra mastercard discount viagra offers discount viagra online discount viagra or cialis discount viagra order viagra discount viagra discount viagra perscription drug discount viagra pharmacy online discount viagra pills discount viagra prescription drug discount viagra sale discount viagra sale online discount viagra sales discount viagra sales online discount viagra uk discount viagra viagra discount viagra wholesale stores discount pharmacy order 50mg viagra order cheap viagra order cheap viagra fas order cialis and viagra order discount viagra order forms for buying viagra order generic viagra order generic viagra online order mexican viagra order order viagra order pfizer viagra with mastercard order phizer viagra order prescription viagra order prescription viagra without order site viagra order status viagra order telephone viagra overnight delivery order uk viagra order viagra order viagra 1 order viagra air travel order viagra buying viagr order viagra buying viagra uk order viagra canada order viagra cheap order viagra cialis levitra pharmacy order viagra here order viagra international ships order viagra licensed pharmacies online order viagra now order viagra now money order viagra now viagra money order order viagra on line order viagra on-line order viagra online order viagra online a href order viagra online consumer discount rx order viagra online consumer rx order viagra online in wisconsin order viagra online no rx prescription order viagra online uk order viagra onlines order viagra or levitra order viagra overnight delivery order viagra overnight shipping order viagra prescription order viagra softtabs order viagra uk order viagra usa order viagra viagra order viagra viagra online order viagra with mastercard buy viagra and cilas usa buy viagra and overseas buy viagra at safeway buy viagra at the best price buy viagra australia buy viagra australian buy viagra bradenton buy viagra buy cheap viagra index buy viagra by pill buy viagra canada buy viagra cheap buy viagra cheap india pharmacy buy viagra cheap online buy viagra cheap prices over sea generic viagra over the counter drug to viagra over the counter viagra in europe over the counter viagra london over the counter viagra substitute over the counter viagra substitutes buy 100 mg viagra viagra and cialas viagra and cialis viagra and cialis and viagra and cialis cheap viagra and cialis together viagra and flomax viagra and generic viagra and generic drug viagra and hair loss viagra and hearing loss viagra br viagra brand viagra brands viagra brazil cipro 20 cheapest viagra tablets