Storing and retrieving data is a common problem. Fortunately, Android comes with a built-in SQLite database…somebody say ..”holy cow batman- kaboom!”

Active record (AR) is a design pattern for Object-Relational modelling (ORM) conceived by Martin Fowler. It gained popularity due in part to the rise of the Ruby on Rails framework with the inclusion of an aptly name gem called …mmh activerecord no surprise.

AR is usually thought of as the M…in MVC (Model-View-Controller) pattern handling the CRUD (Create, Read, Update, Delete) interactions with the back-end database. ..(ok enough acronyms)

Simple usage pattern:

  1. Initialize the database and its connection
  2. Create a class extending an ActiveRecordBase
  3. Set your attributes on the object
  4. Save the attributes as a record in the database

Android ActiveRecord: http://code.google.com/p/android-active-record/

Getting the source code from SVN (require Subversion (svn) installation)
Copy-n-Paste and hit Enter:

svn checkout http://android-active-record.googlecode.com/svn/trunk/ android-active-record-read-only

Now for some details:
NOTE: All attributes must be public for 2 reasons:

  • allows direct access to the attribute/field
  • most importantly for Java Reflection purposes to occur smoothly

1. Initialize the database and its connection

private void initDatabase() throws ActiveRecordException
			{
				Log.d(tag, "initDatabase()");

				this.ctx = getApplicationContext();
				this.builder = new DatabaseBuilder(dbName);

				// Setup the builder
				Database.setBuilder(this.builder);

				Log.d(tag, "opening ActiveRecordBase");
				this.conn = ActiveRecordBase.open(ctx, dbName, dbVersion);
			}

2. Create a class extending ActiveRecordBase

 

import java.sql.Timestamp;
import org.kroz.activerecord.ActiveRecordBase;
import org.kroz.activerecord.Database;
public class Note extends ActiveRecordBase
{
     // public for AR-access
     public String text;
     public Timestamp date;

     public Note()
        {
          // EMPTY
         }

     public Note(Database db)
       {
           super(db);
        }

     @Override
     public String toString()
        {
           return "Date: " + this.date.toString() + "\n" + "Note: " + this.text;
         }
}

3 & 4. Set the attributes on the created object and call the save() method on the object

    // Create a Note entry by requesting it from the database connector
    Note ent = conn.newEntity(Note.class);

    // create a java calendar instance
    Calendar calendar = Calendar.getInstance();
    Date now = calendar.getTime();

    // Set the attributes
    ent.date = new java.sql.Timestamp( now );  // Set the date
    ent.text = "Fred Flinstone";      // Set the text
    ent.save();      // Save the object to the database

Update:
Will be starting a NEW SERIES on using Android-ActiveRecord!

NEXT – https://w2davids.wordpress.com/activerecord-android-intro/