OrmLite for Android Guide

OrmLite for Android is an object-relational mapping framework that can make it easier to work with SQLite on Android. I suggest using this ORM library only if you are familiar with OrmLite for Java.

Installation & Configuration

Add the following line to build.gradle file:

compile 'com.j256.ormlite:ormlite-core:4.48'
compile 'com.j256.ormlite:ormlite-android:4.48'

Create a Model

OrmLite use annotation to map model class. We will create a table named “cars” and map the Car class to this table.

@DatabaseTable(tableName = "cars")
public class Car {

@DatabaseField(generatedId = true)
private Long id;

@DatabaseField
private String name;

@DatabaseField
private String brand;

//getters and setters go below here

}

Create Database Configuration Script

This must be run as a Java application. It is kind of similar to greenDAO’s generator class.

Firstly, create OrmLiteConfigureUtils class that extends OrmLiteConfigUtil.

public class OrmLiteConfigureUtils extends OrmLiteConfigUtil {

//models to use for creating ormlite_config.txt file
private static final Class<?>[] classes = new Class[]{Car.class};

public static void main(String[] args) throws IOException, SQLException {

//create full path to ormlite_config.txt file
String pathToConfig = System.getProperty("user.dir") + "/app/src/main/res/raw/ormlite_config.txt";

File configFile = new File(pathToConfig);

//we delete and update with new file for every new run
if (configFile.exists()) {
configFile.delete();
configFile = new File(pathToConfig);
}

//writeConfigFile writes all necessary info to the configuration file
writeConfigFile(configFile, classes);
}
}

Next, we will run this class as a separate application to generate the configuration file.

Choose “Run” > “Edit Configurations…” > Click on the “+” symbol > Choose “Application” > Set path to OrmLiteConfigureUtils on Main Class field and set to “app” on “Use classpath of module”.

ormlite_application

Let’s run this stand-alone application to get the configuration file. On the Run bar, select “OrmLiteConfigureUtils” instead of “app” then click the “Run” symbol. The configuration file will be generated. And here is the content of my ormlite_config file after running:

#
# generated on 2016/08/11 08:31:46
#
# --table-start--
dataClass=com.androidnames.ormexamples.Car
tableName=cars
# --table-fields-start--
# --field-start--
fieldName=id
generatedId=true
# --field-end--
# --field-start--
fieldName=name
# --field-end--
# --field-start--
fieldName=brand
# --field-end--
# --table-fields-end--
# --table-end--
#################################

Create DAO Class

Create a class that extends OrmliteOpenHelper which is used to manage the interaction between the java objects and the database.

public class CarOpenHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "cars_db";
private static final int DATABASE_VERSION = 1;

private Dao<Car, Long> carDao;

public CarOpenHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
//@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {

//creates the Car table
TableUtils.createTable(connectionSource, Car.class);

} catch (SQLException e) {
e.printStackTrace();
}
}

//@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
//delete then create new database when there is new schema update
TableUtils.dropTable(connectionSource, Car.class, false);
onCreate(database, connectionSource);

} catch (SQLException e) {
e.printStackTrace();
}
}

public Dao<Car, Long> getDao() throws SQLException {
if(carDao == null) {
carDao = getDao(Car.class);
}
return carDao;
}
}

CRUD Operations

try {

//create DAO object
CarOpenHelper carOpenHelper = OpenHelperManager.getHelper(this,
CarOpenHelper.class);
Dao<Car, Long> carDao = carOpenHelper.getDao();

/*
** create
*/
Car car = new Car("Sonata", "Huyndai");
carDao.create(car);

/*
** read
*/
Car car2 = carDao.queryForId((long) 1);
List<Car> allCars = carDao.queryForAll();
List<Car> carsHyundai = carDao.queryForEq("brand", "Huyndai");

/*
** update
*/
car2.setBrand("Ford");
int updated = carDao.update(car2);
//or
UpdateBuilder<Car, Long> updateBuilder = carDao.updateBuilder();
updateBuilder.where().eq("id", 1).and().eq("brand", "Huyndai");
updateBuilder.updateColumnValue("name", "Sonata 2016");
updateBuilder.update();

/*
** delete
*/
carDao.delete(car);
//or
DeleteBuilder<Car, Long> deleteBuilder = carDao.deleteBuilder();
deleteBuilder.where().eq("name", "Sonata 2016");
deleteBuilder.delete();

} catch (SQLException e) {
e.printStackTrace();
}

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close