ORMLite in android for making sqlite database operation Easier





ORMLite is lightweight Java ORM supports for android Sqlite Database.The full form of ORMLite is Object Relational Mapping Lite(ORMLite).and it provides some light weight functionality to store and retrieve Java Objects.And it avoiding the complexity and more standard Object Relational Mapping.

ORMLite supports more than one database using JDBC and also sqlite with native calls to android database APIs..


                             


ORMLite simply add objects of java using annotations.and its have powerful abstract Database Access Object classes.also provides simple and  flexible query using QueryBuilder.Auto generates SQL to create and drop database tables.and its have basic supports for database transactions.



ORMLite Supports MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and Sqlite and can be extended to additional databases relatively easily.
Provisional support for DB2, Oracle, ODBC, and Netezza

first of all you will have write the database helper class by extending the OrmLiteSqliteOpenHelper following is the code snipper for Database Helper.java


package com.androidblazin;
import java.sql.SQLException;
import java.util.List;

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.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
 
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
 
 private Context _context;
 private static final String DATABASE_NAME = "ormliteandroid.db";
 private static final int DATABASE_VERSION = 1;
 
 private Dao simpleDao = null;
 private RuntimeExceptionDao simpleRuntimeDao = null;
 
 public DatabaseHelper(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
  _context = context;
 }
 
 public Dao getDao() throws SQLException {
  if (simpleDao == null) {
   simpleDao = getDao(Person.class);
  }
  return simpleDao;
 }
 
 public RuntimeExceptionDao getSimpleDataDao() {
  if (simpleRuntimeDao == null) {
   simpleRuntimeDao = getRuntimeExceptionDao(Person.class);
  }
  return simpleRuntimeDao;
 }
 
 //method for list of person
 public List GetData()
 {
  DatabaseHelper helper = new DatabaseHelper(_context);
  RuntimeExceptionDao simpleDao = helper.getSimpleDataDao();
  List list = simpleDao.queryForAll();
  return list;
 }
 
 //method for insert data
 public int addData(Person person)
 {
  RuntimeExceptionDao dao = getSimpleDataDao();
  int i = dao.create(person);
  return i;
 }
 
 //method for delete all rows
 public void deleteAll()
 {
  RuntimeExceptionDao dao = getSimpleDataDao();
  List list = dao.queryForAll();
  dao.delete(list);
 }
 
 @Override
 public void close() {
  super.close();
  simpleRuntimeDao = null;
 }
 
 @Override
 public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
  try {
   Log.i(DatabaseHelper.class.getName(), "onCreate");
   TableUtils.createTable(connectionSource, Person.class);
  } catch (SQLException e) {
   Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
   throw new RuntimeException(e);
  }
 }
 
 @Override
 public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
  try {
   Log.i(DatabaseHelper.class.getName(), "onUpgrade");
   TableUtils.dropTable(connectionSource, Person.class, true);
   onCreate(db, connectionSource);
  } catch (SQLException e) {
   Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
   throw new RuntimeException(e);
  }
 }
}
Create the Object of the class person which will be having the paramater values like name and ID Preson.java
package com.androidblazin;

import com.j256.ormlite.field.DatabaseField;

public class Person {

 @DatabaseField(generatedId = true)
 private int id;
 @DatabaseField
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String firstname) {
  this.name = firstname;
 }

}

Activity for the above combination will be as follows MainActivity.java
package com.androidblazin;

import java.util.List;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {
 EditText etEntry;
 ListView listView;
 NameAdapter adapter = null;
 DatabaseHelper helper;
 List list;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  listView = (ListView) findViewById(R.id.listView1);
  listView.setOnItemClickListener(this);

  etEntry = (EditText) findViewById(R.id.etentry);

  helper = new DatabaseHelper(getApplicationContext());

  setDataToAdapter();

 }

 public void adddata(View v) {
  String strName = etEntry.getText().toString().trim();
  if (TextUtils.isEmpty(strName)) {
   showToast("Please Add your Name!!!");
   return;
  }

  Person person = new Person();
  person.setName(strName);

  helper.addData(person);

  showToast("Data Successfully Added");

  setDataToAdapter();

 }

 private void setDataToAdapter() {

  list = helper.GetData();

  adapter = new NameAdapter(this, R.layout.row, list);
  listView.setAdapter(adapter);

 }

 private void showToast(String msg) {
  Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
 }

 public void deletedata(View v) {

  list = helper.GetData();

  if (null != list && list.size() > 0) {
   AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
     .create();
   alert.setTitle("Delete ?");
   alert.setMessage("Are you sure want to delete All data from Database");

   alert.setButton("No", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
     dialog.dismiss();
    }
   });
   alert.setButton2("Yes", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
     dialog.dismiss();

     helper.deleteAll();
                    etEntry.setText(""); 
     showToast("Removed All Data!!!");

     setDataToAdapter();
    }
   });
   alert.show();
  } else {
   showToast("No data found from the Database");
  }
 }

 @Override
 public void onItemClick(AdapterView parent, View view, int position,
   long id) {
  showToast(list.get(position).getName());
 }
}

The Adaptor for the class is as follows NameAdapter.java
package com.androidblazin;

import java.util.List;



import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class NameAdapter extends ArrayAdapter {
    private Context mContext;
    private int row;
    private List list ;
    
 public NameAdapter(Context context, int textViewResourceId, List list) {
  super(context, textViewResourceId, list);

  this.mContext=context;
  this.row=textViewResourceId;
  this.list=list;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  ViewHolder holder;
  if (view == null) {
   LayoutInflater inflater = (LayoutInflater) mContext
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   view = inflater.inflate(row, null);

   holder = new ViewHolder();
   view.setTag(holder);
  } else {
   holder = (ViewHolder) view.getTag();
  }

  
  if ((list == null) || ((position + 1) > list.size()))
   return view; // Can't extract item

  Person obj = list.get(position);
  
  holder.name = (TextView)view.findViewById(R.id.tvname);
  
  if(null!=holder.name&&null!=obj&&obj.getName().length()!=0){
   holder.name.setText(obj.getName());
  }
  
  

  return view;
 }

 public static class ViewHolder {
  public TextView name;
 }
}


Source Code available Here:https://github.com/shir60bhushan/Android-ORMLite-Example

Post a Comment