Deprecation notice

Deprecation Notice: This blog is no longer updated. Please visit my current blog at subfocal.net.

Tuesday, March 1, 2011

Simplifying Android development with ORMLite

So you're building an Android application that needs to store and manipulate persistent local data? On Android, there are only a few mechanisms available for persistent storage. Simple key/value storage is handled using SharedPreferences, basic filesystem access is available for flat files, and finally, SQLite is there for your serious data storage needs.

SQLite is a fantastic little database engine, as you probably know. Despite its simple-sounding name, it has a robust feature set, good performance, and is extremely stable (it's possibly the most rigorously tested OSS project I've seen). I'll assume for the moment that if you're a software engineer in 2011, you are comfortable with relational databases and have a good understanding of the value of ORM (Object Relational Mapping). If not, it's worth it to familiarize yourself with the concept on Wikipedia.

Enter ORMLite

ORMLite is an ORM for SQLite (I guess that was obvious from the name). Originally, it was developed using the JDBC drivers to talk to SQLite, not specifically for Android. The Android SDK makes available the java.sql.* classes, but they are undocumented and unsupported. Intead, Android makes available the proprietary android.database.sqlite.* API, which is basically your only way to do database storage.

Fortunately for us, in September 2010, Kevin Galligan took the initiative to add Android support to ORMLite, using the Android-specific database APIs. As a result, Android developers everywhere can use this great little ORM in their applications!

Getting Started with ORMLite

Pulling ORMLite into your project is simple: go to the Sourceforge files area and grab the latest ormlite-android package (4.14 at the time of this post). You only need the ormlite-android-4.14.jar, not the ormlite-core or any other packages. Drop the jar file into your project's libs/ subdirectory and you're ready to start.

ORMLite takes advantage of Java's reflection API, combined with annotations, to make it very easy to use. Here's an example of an object that can be written and read to the database via ORMLite:

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "people")
public class Person {

    // Constructor and other Person methods...

    @DatabaseField(columnName = "id", id = true, generatedId = true)
    private int m_id;

    @DatabaseField(columnName = "first_name")
    private String m_firstName;
   
    @DatabaseField(columnName = "last_name")
    private String m_lastName;

    @DatabaseField(columnName = "organization_id", canBeNull = false)
    private Organization m_organization;
}

In this stripped down example, there are a few things to notice. First: This is great! Just annotate my class as a table and its members as fields and we're most of the way there!

The second thing to notice is that ORMLite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).

Finally, note that the last field, m_organization, is a reference to another object in the application. ORMLite recognizes this as a foreign key reference, and that the column actually refers to an id in another table. When you read a Person from the ORM, m_organization will refer to an Organization instance with only its id field populated. You can populate the rest of the fields by calling refresh() on the organization DAO.

Interacting with the database is done through a DAO (Data Access Object) which exposes operations like create, update, delete, and more general purpose objects like QueryBuilder. Here's an example of creating a DAO and using it to create a Person in the database:

import java.sql.SQLException;
import com.j256.ormlite.android.AndroidConnectionSource;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;

...

    public void createPerson(Person person) {
        ConnectionSource source = new AndroidConnectionSource(m_helper);
        try {
            DAO personDao =
                    BaseDaoImpl.createDao(source, Person.class);
            personDao.create(person);
        } catch (SQLException e) {
            // Handle exception
        }
    }

It doesn't get much simpler. Note that ORMLite uses the helper object that you get from your SQLite database object to actually interact with the database.

Further Resources

Hopefully this is enough to whet your appetite and get you started. I plan to write some more posts about this topic, giving more in-depth examples and covering cases that aren't as simple.

For more information on using ORMLite with Android, check out these pages:

7 comments:

  1. Just dropping in with some other info about managing SQLite connecitons:

    http://www.touchlab.co/blog/android-sqlite-locking/
    http://www.touchlab.co/blog/single-sqlite-connection/
    and the big stackoverflow post about it...
    http://stackoverflow.com/questions/2493331/what-is-best-practice-with-sqlite-and-android/3689883#3689883

    ReplyDelete
  2. Very informative post especially for android developers. I am working in Android Application Development for about one year now and still was unaware of this concept. ORMLite works as a JDBC driver for SQLite. It's really fantastic.

    ReplyDelete
  3. Mike

    Here is an ORM that works with Sqlite
    https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. I have gone through Siminov Android ORM, it is open source framework with proper user guide and documentation. It is easily configurable, handle application deployment, support multiple schemas and many more. I found it very useful and easy to use.Good thing is same available on other platforms also e.g iOS, Windows 8. I suggest you to try this, you will definitely find it useful and this ORM may solve your problems.

    You can check this link "http://siminov.github.io/android-orm".

    ReplyDelete
  6. Hi, you can check out https://androyiid.com - ORM form Android based on Yii conventions.

    ReplyDelete
  7. Before an App is released, the developer needs to make sure their App is as defect-free as you can. As being a specialist Android App Tester, you'll find numerous defects discovered that could have quickly been detected in the event the App was examined prior to rushing it out for launch.
    showboxdownloadsapp.com

    ReplyDelete