Saturday, March 10, 2012

Data access on android made easy with OrmLite

OrmLite is a wonderful Object Relational Mapper available for the android operating system.

If your using the normal methods to access the sqlite database, then you are bound to find the
process very tedious.I realized i needed an orm when i found myself writing redundant code and it came to my attention that i was actually writing my own orm.

OrmLite is suited for android because it is lightweight and therefore easy to import to an android project.
Furthermore it uses java annotations to mark classes to be persisted which make your code look clean and easier to understand.

import com.j256.ormlite.field.DatabaseField;
public class Customer { @DatabaseField int id; @DatabaseField String name; @DatabaseField String country; @DatabaseField String phone; @DatabaseField String address; @DatabaseField String businessName; Customer(){ //used by ormlite } @Override public String toString(){ return this.name; } }
To create a table we use TableUtils' createTable method
TableUtils.createTable(connectionSource, Customer.class);
Data access is done using Daos(Data access Object),these offer convenient methods for querying, creating, deleting... objects on the sqlite database
private Dao<Customer, Integer> customersDao = getDao(Customer.class);

customersDao.create(customer);


customersDao.delete(customer);

customersDao.queryForAll();



In conclusion, using ormlite saves more time and is more convenient.

No comments:

Post a Comment