Android DataServices – DB4O

You’ve been through the Notepad example, and you’ve seen my enhancements in the previous post.  But what if you don’t want to have to worry about schema updates and figuring out how to store dates/images/whatever in SQLite?  What if you just want to store your objects without all of the SQL-hassle?

Enter Object Oriented Databases.

OODBs are great for small and simple databases, letting you write the fun(ctional) code without the drag of SQL.  We’re not talking ORM or Hibernate, with cleverly-hidden SQL.  Just simple store(MyObject) and we’re done.

The source code is found in the same place as the DataServices and SQLite project:http://svn.hat6.com/hat6public/DataServiceExample/trunk.
For all of this wonderful functionality, we’ll be using DB4O.  They even have a page dedicated to Android, though the source they provide won’t build.

The code matches the DataService interface I provided earlier, so if you’ve read through the SQLite post, you should be able to scan this easily. This file weighs in at just a hair over 200 lines, and a big chunk of that is Exception handling and Comments. So, without further ado, I present to you a working DB4O Android Implementation:

package com.hat6.dataServiceExample.model;

import java.util.List;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.instrumentation.core.Db4oClassSource;

import android.content.Context;
import android.util.Log;

public class ReminderDB4OImpl implements IReminderDataService {

	//TAG for logging.
    private static final String TAG = "ReminderDB4OImpl";
    /**
     * Static variables holding information about our database itself.
     * NAME and TABLE are now used to determine where the DB file lives in the filesystem
     * VERSION allows our app to know if it has to perform any upgrades
     * 		(Though right now, we aren't using it)
     */
    private static final String DATABASE_NAME = "hatsixExamples";
    private static final String DATABASE_TABLE = "remindersDS";
    private static final int    DATABASE_VERSION = 1;

	/**
	 * Context is needed when interacting with the DB
	 */
	private final Context mCtx;
    /**
     * The actual Database.
     */
	private static ObjectContainer _container = null;

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public ReminderDB4OImpl(Context ctx) {
		mCtx = ctx;
		open();
		Db4oClassSource dbocs; //DB40 crashes if we don't force this to be compiled in.
	}

    /**
     * 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)
     */
    public IReminderDataService open() {
		long startTime = 0;
    	try {
    		if(_container == null){
    			startTime = System.currentTimeMillis();
    			_container = Db4o.openFile(configure(), db4oDBFullPath());
    		}
    	} catch (Exception e) {
        	Log.e(TAG, e.toString());
        	return null;
        }
    	Log.d(TAG, "Database opened: " + startTime);

        return this;
    }

    public void close() {
    	if(_container != null){
    		long startTime = System.currentTimeMillis();
    		_container.close();
    		Log.d(TAG, "Database committed and closed: " + startTime);
    		_container = null;
    	}
    }

    /**
     * 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) {
        if (_container != null){
	        try {
	        	_container.store(r);
	        	_container.commit();
	        	Log.d(TAG, "Created selected object: " + r.getTitle());

			} catch (Exception e){
				Log.d(TAG, "Reminder could not be created: " + r.getTitle());
				long l = -1;
				return l;
			}
        }
    	return r.getId();
    }

    /**
     * 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(){
        List<Reminder> list = _container.query(new com.db4o.query.Predicate<Reminder>() {
			private static final long serialVersionUID = 1L;
			public boolean match(Reminder r) {
        		return true;
        	}
        });
    	return list;
    }
    /**
     * Fetch Individual Reminder.  We take the 'query by example' approach, where we pass in
     * a Reminder.  DB40 truly allows us to do query by example, allowing us to search by
     * and piece of data.  We return the first result, if any.
     *
     * @param r Reminder with data set to the Reminder we want fetched.
     * @return Reminder that we were searching for, or null if not found.
     */
    public Reminder fetchReminder(Reminder r){
    	if (_container != null){
	        try {
	        	ObjectSet<Reminder> os = _container.queryByExample(r);
	        	return os.get(0);
			} catch (Exception e){
				Log.d(TAG, "Reminder not found: " + r.getTitle());
				return null;
			}
        }
    	return null;
    }
    /**
     * 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) {
        if (_container != null){
	        try {
	        	_container.store(r);
	        	_container.commit();
	        	Log.d(TAG, "Updated selected object: " + r.getTitle());

			} catch (Exception e){
				Log.d(TAG, "Reminder not found: " + r.getTitle());
				return false;
			}
        }
    	return true;
    }

    /**
     * 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) {
        if (_container != null){
	        try {
	        	_container.delete(r);
	        	_container.commit();
	        	Log.d(TAG, "Deleted selected object: " + r.getTitle());

			} catch (Exception e){
				Log.d(TAG, "Reminder not found: " + r.getTitle());
				return false;
			}
        }
    	return true;
    }

    /**
     * configure creates a new Configuration and sets some parameters, namely that
     * the 'title' should be indexed, and that the DB file should not be locked
     * @return Configuration for the OODB
     */
	private static com.db4o.config.Configuration configure(){
		com.db4o.config.Configuration configuration = Db4o.newConfiguration();
    	configuration.objectClass(Reminder.class).objectField("title").indexed(true);
    	configuration.lockDatabaseFile(false);
    	return configuration;
    }

	/**
	 * db4oDBFullPath returns the path to the DB File in the Context's path.
	 * @return String for the Database.
	 * @throws Exception
	 */
	private String db4oDBFullPath() throws Exception {
		if (mCtx == null){
			throw new Exception("Db4o Module not initialized");
		}
		return mCtx.getDir(DATABASE_NAME, Context.MODE_PRIVATE) + "/"  + DATABASE_TABLE + ".db4o";
	}

}

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