Persistence on Android using ORMlite

 

Everyone knows the hassle of persisting objects to relational databases. Who hasn’t spent hours, days and (let’s be honest) weeks fighting object-relational mappers? It apparently is a hard and time consuming task, often times a real pain in the a** and subject to critic and hate. There are plenty good ORM mapping tools out there. JPA, Hibernate, you name it.

 

In this post I will present you a simple lightweight one to use with your Android projects: ORMlite for Android. I recently used it in one of my open source Android projects and it’s quite simple to use. I will use that project as an example and give you a step-by-step introduction on how to use ORMlite to easily store your data in a SQLite database on Android.

 

First, you will need to add the ORMlite library to your project. When using Gradle, all you have to do is to add the dependency to your gradle build file.

dependencies {
    compile 'com.j256.ormlite:ormlite-android:4.48'
}

 

Then you need to annotate the data model you want to persist, so that ORMlite knows what and how to persist. In the given example we are storing time trackings with a name, a duration and a timestamp. There are two things to annotate. The class itself and the fields we want persisted. The class is to be annotated with @DatabaseTable along with a name for the database table we want to store this kind of data in. And the fields need to be annotated with @DatabaseField . That’s basically it. We want to make sure that there is a default constructor with at least package visibility and getter and setter methods so that ORMlite is able to instantiate and fill them. And we declare one of the fields the ID – what we are querying for later – or have IDs generated for us. And optionally we could specify how the fields are to be stored. So, this would be it:

@DatabaseTable(tableName = "timetracking")
public class Tracking {

    @DatabaseField(id = true)
    private long created;

    @DatabaseField
    private String title;

    @DatabaseField
    private long duration;

    Tracking() {
    }

    // ... and getter/setter methods
}

 

Now we can let ORMlite do its work. Instead of extending our database helper from Android’s SQLiteOpenHelper directly, we use the OrmLiteSqliteOpenHelper wrapper that comes with the library. All the Android’s SQLiteOpenHelper goodies (passing database path and version in the constructor, handling onCreate and onUpgrade, etc.) remain as usual. What changes at this point is that we can have ORMlite do the low level SQL lifting for us. To create our database table we simple tell ORMlite that he should take care of it. The ConnectionSource is passed along by the wrapper and with the annotations on the Tracking class we did earlier ORMlite knows where and how to store our data:

@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    TableUtils.createTable(connectionSource, Tracking.class);
}

 

With this all the ground work is done and we can begin persisting data. A data access object is provided by the wrapper which we can just give our object to persist and that’s all we need to do.

public void storeTracking(Tracking newTracking) {
    try {
        getDao(Tracking.class).createOrUpdate(newTracking);
    } catch (SQLException e) {
    }
}

 

And querying stored data is just as easy. We get hold of the same data access object like before, call the querybuilder – which we optionally can feed with query parameters (order by, limit, where clauses, and what have you) – and execute the query.

public List<Tracking> fetchTrackings() {
    List<Tracking> trackings = new ArrayList<>();
    try {
        trackings = getDao(Tracking.class).queryBuilder().query();
    } catch (SQLException e) {
    }
    return trackings;
}

 

And that’s the introduction to persisting data to SQLite database on Android with ORMlite. We’ve seen how to add ORMlite to your Android project, set up the data model to store, and persist and query data using the provided DAO. The complete working example is available on Github.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *