ORMLite with Android
I am working on application which requires a database. Android supports SQLite and we have to make do with it. Writing database queries can create a lot of boilerplate code and can be really difficult to debug. I was looking for some sort of ORM library for android. I came around few of them. One of them was GreenDAO
. It seemed very promising but I couldn’t manage to get it working after spending couple of days. I decided to give ORMLite a shot. The library is very stable and uses annotations. It was really easy to implement everything so I decided to stick with it.
Model
To use ORMLite, you first need to create your model classes. A sample model class would like this.
- ORMLite needs an empty constructor
- ORMLite generally expects your variables to be public, but you can keep them private with using
useGetSet=true
- You can specify field name to be used in the table with
coulmnName
generatedId = true, allowGeneratedIdInsert = true
will generate Auto Incremental Ids.- To store dates, it is advised to use
java.util.Date
and notjava.sql.Date
. Also, it is advised to keep date withDataType.DATE_LONG
so that you can sort data based on dates.
There isn’t much more to this. This will be your table model.
DatabaseHelper
ORMLite has provided a class OrmLiteSqliteOpenHelper
which I extended to create my own database helper class. This class will call method onCreate
if the database does not exist. It will call onUpgrade
method if you change your database version.
In onUpgrade
method, you need not drop the table and create it again. If you do this, you would also have to take care about not losing the data. ORMLite - Upgrading Your Schema shows a very helpful way to update database without losing the data.
Repository
Repository is the class which you use to query data from the database.
Add Note To Database
GitHub Repository
I have uploaded this code on GitHub with some functionality so that app is responsive. You can fork it here.
Here’s an updated screenshot of the app.
P.S. I have strated to work with RxJava and it has been a joyride!
Playing around with Android UI
Articles focusing on Android UI - playing around with ViewPagers, CoordinatorLayout, meaningful motions and animations, implementing difficult customized views, etc.