Home > Android > Singleton pattern in android database and in general

Singleton pattern in android database and in general

Howdy everyone,
It’s been a long time since i wrote any post.I have been super busy with my projects , i couldn’t manage my time to write any post for my blog.
Today i am going talk a little bit about using singleton pattern.And show you an example of it during the explanation.
Now what is it? and why do you care about it?
First let’s imagine the normal way of doing things if you are novice anough :).
Say my application consist of N number of screen.Now all screens uses an object for accessing some kind of data.If i were novice what i would do is create object of that class in every screen to access those data.
That would create N number of object.
Now since we only need to access some data but not to modify any data of that class object do we really need to create object for that class in every screen.
Of course we do if there is no pattern like singleton šŸ™‚
Now let’s get down to what is it?As i said it’s pattern but more likely a design pattern.
Since we only need to access some data from a class, what this let’s us do is to create one object for the enitre application life cycle.And we can access those data over and over again using only single instance if that class object.
And that is what singleton mean šŸ™‚
Why do u care? Well, i think it’s obvious, isn’t it? Save memory, Reduce complexity of the application….
Let’s see an example,
If you pay attention to class A structure you can see you can’t create any new object by
A object = new A();
Since the contructor is private the only way to get an instance of that class is calling static method getInstance of class A, so now whenever you call A.getInstance() it will return either a new object or an object that already been instantiated.

// Singleton class
    class A{
     public int a = 10;
     private static A a = null;
     private A(){
          a = this;
      }
      public static A getInstance (){
          if ( a == null )
           {
              a = new A ();
            }
        return a;
      }
    }
    // Use of singleton class
   class B{
    int myInt;
      public B(){
         System.out.println(A.getInstance().a+"");
     }
    }

Now let’s see a real exmple that might be helpful to some guys.I made this somedays ago during one of my project and documented it along the way so people who see the code can get a little bit of undertanding, what this class do?

Sqlite database for android in singlton:

package com.project;
/*
@author : Saiful Islam
@mail : saiful103a@gmail.com
*/
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

     // db name for this application

     private static final String DATABASE_NAME = "appdb";

     // version number of this db

     private static final int DATABASE_VERSION = 1;

     // private variable which is going to store the singlton object of this class and return it to caller

     private static DatabaseHelper dbHelper = null;
     // private SQLiteDatabase varaible which is going to be responsible for all our db related operation // no need      touch it

     private static SQLiteDatabase db = null;
   
     // a private contructor which is going to be called from getInstance method of this constructor
     
     private DatabaseHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
         // storing the object of this class to dbHelper
         dbHelper = this;
     }
   
     // Method is called during creation of the database
     /* ***************************
     *
     * BE SURE TO ENTER THE CORRECT CREATE STATEMENT FOR TABLE IN DBTable.java FOR YOUR APPLICATION NEED
     *
     */

     @Override
     public void onCreate(SQLiteDatabase database) {
      DBTable.onCreate(database);
     }
  
     // Method is called during an upgrade of the database,
     // e.g. if you increase the database version

      @Override
      public void onUpgrade(SQLiteDatabase database, int oldVersion,
     int newVersion) {
       DBTable.onUpgrade(database, oldVersion, newVersion);
      }

     // method which is going to be responsible for all our select query
     /* use case:
     * String selectSql = "Select * from table_name";
     * //be careful using try catch:
     * Cursor myCursor = null;
     * try{
     * myCursor = DatabaseHelper.getInstance.executeQuery(selectSql);
     * // ..... get the data using cursor from the db
     * }catch(Exception e){
     * e.printStackTrace(); // be sure to check if any exception is thrown and find out what is the reason
     * }finally{ // be sure to close the cursor or else, might get some unexpected behavior
     * // see if cursor really got something when requesting for something and is not closed already, just for    precaution    :)
     * if(myCursor!=null && !myCursor.isClosed){
     * myCursor.close();
     * }
     * }
     */

   public Cursor executeQuery(String sql){
    Cursor mCursor =db.rawQuery(sql, null);
     return mCursor;
   }
     // method which is going to be responsible for all insert, update and delete query
     /* use case:
     * String dmlQuery = "Insert into table_name values(....";
     * DatabaseHelper.getInstance.executeDMLQuery(dmlQuery);// will return true or false based on the action succeeded    or   not if checked?
     */

    public boolean executeDMLQuery(String sql){
    try {
      db.execSQL(sql);
       return true;
     } catch (Exception e) {
     // TODO: handle exception
      return false; 
    }
   }

     // will return a singleton object of this class will as well open the connection for convinient

    public static DatabaseHelper getInstance(Context context){
        if(dbHelper==null){
          dbHelper = new DatabaseHelper(context);
           openConnecion();
          }
         return dbHelper;
      }
     // will be called only once when singleton is created
 
    private static void openConnecion(){
          if ( db == null ){
                db = dbHelper.getWritableDatabase();
            }
      }
    // be sure to call this method by: DatabaseHelper.getInstance.closeConnecion() when application is closed by    somemeans most likely
    // onDestroy method of application

     public synchronized void closeConnecion() {
          if(dbHelper!=null){
              dbHelper.close();
                 db.close(); 
                dbHelper = null;
                db = null;
            }
        }
     }
   


package com.project;
/*
@author : Saiful Islam
@mail : saiful103a@gmail.com
*/
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBTable {
   // Database creation SQL statement
   // Modify this class based on the need of the app's database

      private static final String CREATE_ANTLER_TABLE = "create table if not exists mytable "
          + "(_id INTEGER PRIMARY KEY autoincrement,"
          + "name VARCHAR(20),"
          +"value VARCHAR(30));";
   
      public static void onCreate(SQLiteDatabase database) {
          database.execSQL(CREATE_ANTLER_TABLE);
      }
   
      public static void onUpgrade(SQLiteDatabase database, int oldVersion,
   int newVersion) {
         Log.w(DBTable.class.getName(), "Upgrading database from version "
           + oldVersion + " to " + newVersion
           + ", which will destroy all old data");
           database.execSQL("DROP TABLE IF EXISTS todo");
           onCreate(database);
         }
    }

I hope this help some people as it helped me.
And “HAVE A GOOD PROGRAMMING”

Advertisements
Categories: Android
  1. Manek
    April 27, 2013 at 8:30 pm

    Very clear tutorial. šŸ™‚ Thanks.

  2. July 29, 2013 at 5:25 am

    The more you can fill your time with productive and interesting tasks,
    the less likely you are to feel the urge to contact him.
    You may also screen and counsel prospective employees.

    Unfortunately, in the field of psychology, time is not given so much
    importance.

  3. gaber
    September 2, 2013 at 7:20 pm

    Thanks

  1. No trackbacks yet.

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

%d bloggers like this: