Monday, 16 December 2013

Using db4o in Android

db4o is a Object oriented database. This tutorial was written to get you started with db4o as quickly as possible. Before you start, please make sure that you have downloaded the latest db4o distribution from the db4objects website.
In this tutorial I have used db4o-8.0.184.15484-all-java5.jar from java2s.com

Then kindly put the file in your project's lib folder and configure project's Build Path.

Enough, Let us start !!!

1. Create a class to configure db4o. I named it as Db4oHelper.

Code:

Db4oHelper.java


import java.io.IOException;

import android.content.Context;
import android.util.Log;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

public class Db4oHelper {

 private static ObjectContainer oc = null;
 private Context context;

 /**
  * @param ctx
  */
 public Db4oHelper(Context ctx) {
  context = ctx;
 }

 /**
  * Create, open and close the database
  */
 public ObjectContainer db() {

  try {
   if (oc == null || oc.ext().isClosed()) {
    oc = Db4oEmbedded.openFile(dbConfig(), db4oDBFullPath(context));
   }

   return oc;

  } catch (Exception ie) {
   Log.e(Db4oHelper.class.getName(), ie.toString());
   return null;
  }
 }

 /**
  * Configure the behavior of the database
  */

 private EmbeddedConfiguration dbConfig() throws IOException {
  EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
  configuration.common().objectClass(Student.class).objectField("name")
    .indexed(true);
  configuration.common().objectClass(Student.class).cascadeOnUpdate(true);
  configuration.common().objectClass(Student.class)
    .cascadeOnActivate(true);
  return configuration;
 }

 /**
  * Returns the path for the database location
  */

 private String db4oDBFullPath(Context ctx) {
  return ctx.getDir("data", 0) + "/" + "myDatabase.db4o";
 }

 /**
  * Closes the database
  */

 public void close() {
  if (oc != null)
   oc.close();
 }
}


2. Create a class to access db4o. I named it as DB4OProvider.

Code:

DB4OProvider.java


import java.util.List;

import android.content.Context;

public class DB4OProvider extends Db4oHelper {

 private static DB4OProvider provider = null;

 //configure Db4oHelper by Passing Context.
 public DB4OProvider(Context ctx) {
  super(ctx);
 }

 public static DB4OProvider getInstance(Context ctx) {
  if (provider == null)
   provider = new DB4OProvider(ctx);
  return provider;
 }

 //This method is used to store the object into the database.
 public void store(Student exercise) {
  db().store(exercise);
 }

 //This method is used to delete the object into the database.
 public void delete(Student exercise) {
  db().delete(exercise);
 }

 //This method is used to retrive all object from database.
 public List<Student> findAll() {  
  return db().query(Student.class);
 }

 //This method is used to retrive matched object from database.
 public List<Student> getRecord(Student s) {  
  return db().queryByExample(s);
 }
// public ObjectSet<Student> getAllData() {
//  Student proto = new Student(null, null, 0);
//  ObjectSet result = db().queryByExample(proto);
//  return result;
// }

}


3. Create a Object class. I named it as Student.

Code:

Student.java

public class Student {

 String name;
 String number;
 int age;

 //constructor, to initialize all variables
 public Student(String name, String number, int age) {
  this.name = name;
  this.age = age;
  this.number = number;
 }

 //Object will return in this format.
 public String toString() {
  return name + "/" + number + "/" + Integer.toString(age);
 }
}


4. Create Activity class to work on. In my case it is MainActivity.java

Code:

MainActivity.java

package com.db4o.db4oexample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

 DB4OProvider ep;
 EditText et_Name, et_Age, et_Number;
 Student c;
 String name = "", number = "";
 int age = 0;
 ArrayList<HashMap<String, Object>> mylist;
 ListView mListView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  et_Name = (EditText) findViewById(R.id.editText1);
  et_Age = (EditText) findViewById(R.id.editText2);
  et_Number = (EditText) findViewById(R.id.editText3);

  ep = new DB4OProvider(this);
 }

 public void onSubmit(View v) {
  name = et_Name.getText().toString();
  age = Integer.parseInt(et_Age.getText().toString());
  number = et_Number.getText().toString();

  c = new Student(name, number, age);
  ep.store(c); // store the database into the database.

  Student s1 = new Student(null, null, 12);// to retrieve object which has
             // age value as 12.
  System.out.println("Get Record : " + ep.getRecord(s1));
  listResult(ep.findAll());// to retrieve all objects.
 }

 // This method is used to display all objects as ListView.
 public void listResult(List<Student> result) {
  mylist = new ArrayList<HashMap<String, Object>>();
  for (Student s : result) {
   HashMap<String, Object> map = new HashMap<String, Object>();
   map.put("name", s.name);
   map.put("age", s.age);
   map.put("number", s.number);
   mylist.add(map);
  }

  ListAdapter adapter = new SimpleAdapter(this, mylist,
    R.layout.list_data, new String[] { "name", "age", "number" },
    new int[] { R.id.tv_name, R.id.tv_age, R.id.tv_num });
  mListView = (ListView) findViewById(R.id.listView1);
  mListView.setAdapter(adapter);
 }

}


And your activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="@string/name" >
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:ems="10"
        android:inputType="number"
        android:hint="@string/age" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:ems="10"
        android:inputType="number"
        android:hint="@string/reg_no" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onSubmit"
            android:text="@string/submit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClear"
            android:text="@string/clear" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="5dp"
        android:background="@drawable/listview_shape"
        android:orientation="vertical" >

        <TextView
            android:background="@drawable/shape_head"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:gravity="center"
            android:textColor="#fff"
            android:textSize="18sp"
            android:text="Records as List" />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

</RelativeLayout>


And your list_data.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="right" >

        <TextView
            android:id="@+id/tv_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>


And here is the shape_head.xml


<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:endColor="#0066CC"
        android:startColor="#003D7A" />

    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:radius="0.1dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

</shape>


And here is the listview_shape.xml


<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:radius="0.1dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

    <solid android:color="#FFFFFF" />

    <stroke
        android:width="1dp"
        android:color="#cccccc" />
</shape>


Sample Screen Shot


I hope this post is useful. kindly share your feedback as comment here.


Thank You