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.
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
- You can specify field name to be used in the table with
generatedId = true, allowGeneratedIdInsert = truewill generate Auto Incremental Ids.
- To store dates, it is advised to use
java.sql.Date. Also, it is advised to keep date with
DataType.DATE_LONGso that you can sort data based on dates.
There isn’t much more to this. This will be your table model.
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.
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 is the class which you use to query data from the database.
Add Note To Database
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!