Wednesday, December 2, 2009

Database Programming in android

Android provides four ways to achieve the persistence.
Preferences - Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.
Databases - Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it
Files - Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.
Network - Data can be stored and retrieved from the network too depending on the availability.    

Preference :
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();


Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE")
;


Creating and Using Databases in Android
Every application uses data, and Android applications are no exception. Android uses the open-source, stand-alone SQL database, SQLite. Learn how to create and manipulate a SQLite database for your Android app.

Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications.

In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the /data/data//databases folder of an Android device. In this article, you will learn how to create and use a SQLite database in Android.

Here we are going to introduce two new class for database programming.
Class 1. Create a SQLiteFactoryManager which is provide the database.
Class 2. Create a DAOHelper which provides CRUD Operation.


Create a SQLiteFactoryManager which is provide the database.
SQLiteFactoryManager is used to create a database and tables
Step 1: Create a SQLConnectionFactory class which extends the SQLiteOpenHelper
        public class SQLConnectionFactory extends SQLiteOpenHelper {

Step 2: Create a database using the SQLiteOpenHelper constructor
        public SQLConnectionFactory(Context context) {
            super(context, DATABASENAME, null, 1);   
        }


Step 3: Create Tables
    db.execSQL(CREATE_USERTABLE);
   

SAMPLE SOURCE   

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class SQLConnectionFactory extends SQLiteOpenHelper {

    private static final String DATABASENAME = "BIRTHDAY";
    private static final String CREATE_USERTABLE = "CREATE TABLE BIRTHDAY(ID INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,NAME TEXT,CATEGORY TEXT,DOB DATE,AGE INTEGER)";
   
    public SQLConnectionFactory(Context context) {
        super(context, DATABASENAME, null, 1);   
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERTABLE);
        Log.d("@G SQLConnectionFactory", " CREATE_USERTABLE Table ");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


Create a DAOHelper which provides CRUD Operation.
Step1: Get the Factory Object from SQLConnectionFactory.
        factoryObj = new SQLConnectionFactory(c);

Step2: Get the readable/writeable database object using the Factory Object.
        public static SQLiteDatabase getReadableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }

        public static SQLiteDatabase getWriteableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }


Step 3: Perform the CRUD operation using SQLite query. insertData,removeData,getData.

Sample Code

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import android.widget.ArrayAdapter;

public class DAOHelper {

    static SQLConnectionFactory factoryObj;
    static SQLiteDatabase database;

    public DAOHelper(Context c) {
        factoryObj = new SQLConnectionFactory(c);
    }

    public static SQLiteDatabase getReadableDataBase(Context c) {
        return factoryObj.getReadableDatabase();
    }

    public static SQLiteDatabase getWriteableDataBase(Context c) {
        return factoryObj.getWriteableDatabase();
    }

    public void insertData(Context c, Object bindValue[]) {
        database = getWriteableDataBase(c);
        SQLiteStatement statement = database
                .compileStatement("SELECT MAX(ID) + 1 FROM BIRTHDAY");
        long taskId = statement.simpleQueryForLong();
        if (taskId <= 0) {
            taskId = 1;
        }
        database.execSQL(
                "INSERT INTO BIRTHDAY(NAME,CATEGORY,DOB) VALUES(?,?,?)",
                bindValue);
    }

    public ArrayList getData(Context c, Object bindValue[]) {
        ArrayList taskNameList = new ArrayList();
        try {
            database = database = getReadableDataBase(c);
            Cursor results = database.rawQuery("SELECT * FROM BIRTHDAY", null);
            if (results.moveToFirst()) {
                for (; !results.isAfterLast(); results.moveToNext()) {
                    taskNameList.add(results.getString(1) + " - "
                            + results.getString(3));
                }
            }
        } catch (Exception e) {
            Log.e("Tasks App", "Unable to to refresh tasks.", e);
        } finally {
            return taskNameList;
        }
    }

    public boolean removeData(Context c, Object bindValue[]) {
        try {
            database = database = getReadableDataBase(c);
            database.execSQL("DELETE FROM BIRTHDAY WHERE ID in (?)", bindValue);
        } catch (Exception e) {
            Log.e("Remove Data", "Unable to to DELETE id.", e);
        } finally {
            return true;
        }
    }

}

Hope this is helpful for you



No comments:

Post a Comment