вівторок, 20 грудня 2011 р.

Using ORMLite in Android projects

(If you just want to start hacking right away please skip this philosophical piece and go straight to the Tutorial)
There are a lot of cases when it makes sense to store data in a mobile app. In iOS you have several ways to do it, including a powerful CoreData framework which allows persisting object graphs of a significant complexity.
In Android there are also several ways to do it, however the most advanced (in terms of flexibility and convenience) way to store structured data in Android is to use an SQLite relational database.

Probably everyone knows this, but still:
SQLite is basically a special file format and a set of APIs implemented in a library that ships with Android OS.  Like most relational databases management systems SQLite API allows to manipulate data with SQL queries.

The programming model in which one has to manipulate data with plain SQL queries inside the application business logic is tedious, inconvenient and outdated.  It should be forbidden to write spaghetti like code filled with SQL-queries in XXI century.  Even if you are completely forced to write SQL queries in code and if you are a good programmer - you will find yourself writing some sort of framework that encapsulates common query routines and allows you to easier do similar operations on different data entities.  What is more tedious, time-consuming and inconvenient - is dealing with SQLite API (anyone ever worked with SQLite C API ?).

The convenient programming model for me is:
- to be able to create/update objects in code and persist them by calling a method on a certain DB-manager object,
- to be able to fetch a set of objects with a certain predicate defined for one/several of the object's fields

This programming model is generally achieved with the help of any persistance/ORM framework such as Hibernate, however the latter is pretty heavy to be used in Android.  There is an excellent alternative called ORMLite.  As the name implies - it is a lightweight ORM framework, and it turns out to be well suited for Android.

Let's do a simple tutorial that will help you get started with using ORMLite in your own project.
The full source code is hosted on GitHub: https://github.com/justadreamer/WishListManager.  I strongly encourage you to download the source code, import it to your Eclipse workspace and play with the ready-made app.  After this I advice to start the project from scratch in another IDE instance and use the source code only in case of uncertainty/confusion, otherwise following the tutorial steps.