Monday, January 28, 2013

ORMLite Android Tutorial

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases.

OVERVIEW

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases ORMLite supports JDBC connections to MySQL, Postgres, H2, SQLite, Derby, HSQLDB, Microsoft SQL Server. ORMLite also supports native database calls on Android Operating System.

Implementatin ORMLite with Android

To get started with ORMLite, We need to download the ORMLite jar files.These can be downloaded from ORMLite release page
Once we download ORMLite we need to add external library to our android project. Put the jar file into your project’s libs/ subdirectory.
We only need the ormlite-android-4.14.jar, not the ormlite-core or any other packages.
Getting Started with  ORMLite
Get started Ormlite we will need to create our own database helper class which should extend the OrmLiteSqliteOpenHelper class. This class creates and upgrades the database when the application is installed and also provide the DAO(Data Access Object) classes used by other classes. The helper class must implement the methods
onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)
onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
onCreate creates the database when app is first installed while onUpgrade handles the upgrading of the database tables when we upgrade our app to a new version.
The helper should be kept open across all activities in the app with the same SQLite database connection reused by all threads. If we open multiple connections to the same database, stale data and unexpected results may occur. It is recommended to use the OpenHelperManager to monitor the usage of the helper – it will create it on the first access, track each time a part of our code is using it, and then it will close the last time the helper is released.
Once we define our database helper and are managing it correctly, We will use it in our Activity classes. An easy way to use the OpenHelperManager is to extend OrmLiteBaseActivity for each of your activity classes – there is also OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity. These classes provide a helper protected field and a getHelper() method to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method.


Sample Database Helper 


import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application — change to something appropriate for your app
private static final String DATABASE_NAME = “scotchadmins”;
// any time you make changes to your database, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the any table
private Dao<DemoORMLite, Integer> DemoORMLiteDao = null;
private RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteRuntimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), “onCreate”);
TableUtils.createTable(connectionSource, DemoORMLite.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t create database”, e);
throw new RuntimeException(e);
}
// here we try inserting data in the on-create as a test
RuntimeExceptionDao<DemoORMLite, Integer> dao = getDemoORMLiteDao();
String name = scotchadmins
// create some entries in the onCreate
long date = System.currentTimeMillis();
DemoORMLite demo = new DemoORMLite(name,date);
dao.create(demo);
Log.i(DatabaseHelper.class.getName(), “created new entries in onCreate: “);
}
/**
* This is called when the application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), “onUpgrade”);
TableUtils.dropTable(connectionSource, DemoORMLite.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t drop databases”, e);
throw new RuntimeException(e);
}
}
/**
* Returns the Database Access Object (DAO) for our SimpleData class. It
* will create it or just give the cached value.
*/
public Dao<DemoORMLite, Integer> getDao() throws SQLException {
if (DemoORMLiteDao == null) {
DemoORMLiteDao = getDao(DemoORMLite.class);
}
return DemoORMLiteDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
DemoORMLiteRuntimeDao = null;
}
}

Creating a Table in ORMLite


There are a few things to notice when we use ORMLite
First: We just annotate our class as a table and its members as fields and we’ re almost done with creating a table
The second thing to notice is that ORMLite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).

It is mandatory to have a no argument constructor in our class

public class DemoORMLite {
// Class name will be tablename Fields here
@DatabaseField(generatedId = true, canBeNull = false)
int _id;
@DatabaseField(canBeNull = true)
String first_name;
@DatabaseField(canBeNull = true)
String last_name;
@DatabaseField(canBeNull = true)
Date created;
DemoORMLite() {
}

public DemoORMLite(String name,long date) {
this.first_name = name;
this.last_name = “lastname”;
this.created = new Date(date);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_id);
sb.append(“, “).append(first_name);
sb.append(“, “).append(last_name);
SimpleDateFormat dateFormatter = new SimpleDateFormat(
“MM/dd/yyyy HH:mm:ss.S”);
sb.append(“, “).append(dateFormatter.format(created));
return sb.toString();
}
}
}

Database Operations

Deleting a record in ormlite
DeleteBuilder assists in building sql DELETE statements for a particular table in a  database.
Sample Code that  deletes elements from table in field by arg
DatabaseHelper helper = OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);
Dao dao = helper.getDao(YOUR_CLASS.class);
DeleteBuilder<CanteenLog, Integer> deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq(“FIELD_NAME”, arg);
deleteBuilder.delete();

Query in ORMLite

1.Query for all
returns the list of all records in the table we have inbuild function queryForAll();
// get our dao
RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteDao = getHelper().getDemoORMLiteDao ();
// query for all of the data objects in the database
List<SimpleData> list = simpleDao.queryForAll();
2.Query for id
returns the record corresponding to given id we have inbuild function queryForId(id);
Sample code
TEntity entity = this.dao.queryForId(id)
3.Query for particular field name
here we query for field “lastname” and it returns list of records that have last_name =”lastname”

public List<DemoORMLite> RetrieveByLastName(String lastname)  throws SQLException {
QueryBuilder<TEntity, Integer> queryBuilder = dao.queryBuilder();
List<TEntity> list;
queryBuilder.where().eq(“last_name”, lastname);
list = queryBuilder.query();
return list;
}

No comments:

Post a Comment