Wednesday, February 1, 2012

How to create the Singleton DBAdapter for database in android?

Following is the DBAdapter class for the database..........


public class DBAdapter extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "DataBase.db";
private static final int DATABASE_VERSION = 1;
private static DBAdapter instance;
public Context context;


public static DBAdapter getSharedObject(Context context) {
if (instance == null) {
instance = new DBAdapter(context);
}
instance.context = context;
return instance;
}


public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


public SQLiteDatabase getWritableDatabase() {
SQLiteDatabase sqdb = super.getWritableDatabase();
sqdb.setLockingEnabled(true);
return sqdb;
}


public SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}


@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Table(PamId INTEGER PRIMARY KEY,PamName TEXT NULL)");
}


public void clearDB() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE Table");
this.onCreate(db);
db.close();
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}

No comments:

Post a Comment