Android : Object Relational Mapping Lite (ORM Lite / OrmLite) for JAVA Android


ORMLite is lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages.

website : http://ormlite.com/.

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language

http://en.wikipedia.org/wiki/Object-relational_mapping

Here is example code to help you get going with ORMLite

  1. Create Android Project (I’m using netbeans for  IDE).
  2. Download ormlite-android-4.41.jar  and ormlite-core-4.41.jar.
  3. Add ormlite-android-4.41.jar  and ormlite-core-4.41.jar to the project’s libs folder to include them as libraries.
  4. We will use table Users as simple example, create UserActivity.java then don’t forget to register the UserActivity to the AndroidManifest.xml (I sure you have known about how to do it).
  5. Next create UserHelper.java and UserData.java
  6. Now Open UserData.java and copy the code below, just adjust the modifications to suite your own project if any
    • package com.test.orm;
      /*
       * To change this template, choose Tools | Templates
       * and open the template in the editor.
       */
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import com.j256.ormlite.field.DatabaseField;
      import java.security.NoSuchAlgorithmException;

      /**
       *
       * @author Yusuf
       */
      public class UserData {

          // id is generated by the database and set on the object automagically
          @DatabaseField(generatedId = true)
          public int id;

          @DatabaseField(index = true)
          public String username;

          @DatabaseField()
          public String password;

          @DatabaseField
          public boolean rememberme;

          @DatabaseField
          public long millis;

          @DatabaseField
          public Date created;

          @DatabaseField
          public Date modified;

          UserData() {
              // needed by ormlite
          }

          public UserData(String username, String password, boolean isRemember, long millis) throws NoSuchAlgorithmException {
              this.username = username;
              this.password = password;
              this.rememberme = isRemember;
              this.millis = millis;
              this.created = new Date(millis);
              this.modified = new Date(millis);
          }
      }

  7. Next, let continue by opening UserHelper.java
    • package com.test.orm;

      import java.sql.SQLException;

      import android.content.Context;
      import android.database.sqlite.SQLiteDatabase;
      import android.util.Log;

      import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
      import com.j256.ormlite.dao.Dao;
      import com.j256.ormlite.support.ConnectionSource;
      import com.j256.ormlite.table.TableUtils;
      import java.security.NoSuchAlgorithmException;
      import java.util.logging.Level;
      import java.util.logging.Logger;

      /**
       * 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 UserHelper extends OrmLiteSqliteOpenHelper {

          // name of the database file for your application — change to something appropriate for your app
          private static final String DATABASE_NAME = “binutrifood.db”;

          // any time you make changes to your database objects, you may have to increase the database version
          private static final int DATABASE_VERSION = 1;

          // the DAO object we use to access the UserData table
          private Dao<UserData, Integer> simpleDao = null;

          public UserHelper(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(UserHelper.class.getName(), “onCreate”);
                  TableUtils.createTable(connectionSource, UserData.class);

              } catch (SQLException e) {
                  Log.e(UserHelper.class.getName(), “Can’t create database”, e);
                  throw new RuntimeException(e);
              }
          }

          /**
           * This is called when your 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(UserHelper.class.getName(), “onUpgrade”);
                  TableUtils.dropTable(connectionSource, UserData.class, true);
                  // after we drop the old databases, we create the new ones
                  onCreate(db, connectionSource);
              } catch (SQLException e) {
                  Log.e(UserHelper.class.getName(), “Can’t drop databases”, e);
                  throw new RuntimeException(e);
              }
          }

          /**
           * Returns the Database Access Object (DAO) for our UserData class. It will create it or just give the cached
           * value.
           */
          public Dao<UserData, Integer> getUserDataDao() throws SQLException {
              if (simpleDao == null) {
                  simpleDao = getDao(UserData.class);
              }
              return simpleDao;
          }

          /**
           * Close the database connections and clear any cached DAOs.
           */
          @Override
          public void close() {
              super.close();
              simpleDao = null;
          }
      }

  8. For last go to open main activity named UserActivity.java
    • package com.test.orm;

      import android.app.Activity;
      import android.os.Bundle;
      import android.util.Log;
      import com.j256.ormlite.android.apptools.OpenHelperManager;
      import com.j256.ormlite.dao.Dao;
      import java.security.NoSuchAlgorithmException;
      import java.sql.SQLException;
      import java.util.List;
      import java.util.logging.Level;
      import java.util.logging.Logger;

      public class UserActivity extends Activity
      {
          private UserHelper userHelper = null;
           private static final String TAGS = “ORMLite Lesson. “;
          /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState)
          {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              
              try {
                  // get our dao
                  Dao<UserData, Integer> simpleDao = getHelper().getUserDataDao();
                  // query for all of the data objects in the database
                  List<UserData> list = simpleDao.queryForAll();
                  // our string builder for building the content-view
                  StringBuilder sb = new StringBuilder();
                  sb.append(“got “).append(list.size()).append(” entries in “).append(“user act”).append(“\n”);

                  // if we already have items in the database
                  int simpleC = 0;
                  for (UserData user : list) {
                      sb.append(“——————————————\n”);
                      sb.append(“[“).append(simpleC).append(“] = “).append(“Username: “+user.username+”. pass: “+user.password).append(“\n”);
                      simpleC++;
                  }

                  sb.append(“——————————————\n”);
                  for (UserData user : list) {
                      simpleDao.delete(user);

                      sb.append(“deleted id “).append(user.id).append(“\n”);
                      Log.i(TAGS, “deleting simple(” + user.id + “)”);

                      simpleC++;
                  }
                  
                  for (int i = 0; i < 5; i++) {
                      // create a new simple object
                      long millis = System.currentTimeMillis();
                      UserData simple = new  UserData(“username”+i, “password”+i, true, millis);
                      // store it in the database
                      simpleDao.create(simple);
                      Log.i(TAGS, “created simple(” + millis + “)”);
                      // output it
                      sb.append(“——————————————\n”);
                      sb.append(“created new entry #”).append(i + 1).append(“:\n”);
                      sb.append(simple).append(“\n”);
                      try {
                          Thread.sleep(5);
                      } catch (InterruptedException e) {
                          // ignore
                      }
                  }

                  //tv.setText();
                  Log.i(TAGS, “Log DB : ” + sb.toString());
                  Log.i(TAGS, “Done with page at ” + System.currentTimeMillis());
              } catch (NoSuchAlgorithmException ex) {
                  Logger.getLogger(UserActivity.class.getName()).log(Level.SEVERE, null, ex);
              } catch (SQLException e) {
                  Log.e(TAGS, “Database exception”, e);
                  //tv.setText(“Database exeption: ” + e);
                  return;
              }
              
          }
          
         /**
           * You’ll need this in your class to get the helper from the manager once per class.
           */
          private UserHelper getHelper() {
              if (userHelper == null) {
                  userHelper = OpenHelperManager.getHelper(this, UserHelper.class);
              }
              return userHelper;
          }
          
      }

  9. Now run the Application, and take a look to the console Logs to see the result, you also able check the data directly to the database that you have been created.
  10. That’s all, good luck,for more information please go to the ormlite Official Site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s