Friday 20 April 2012

Create DataBase In Android (Part 1)

Setp by Step Procedure for Create Database in android :-

Setp 1:- Create a new Class Database first

public class Database{
          public Database(Context context)
          {
           }
}

Setp 2:- Create  static class in Database class which extend SQLiteOpenHelper same as below


private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ "          (id INTEGER PRIMARY KEY,title TEXT, type TEXT)");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);


onCreate(db);
}
}


Step 3:- Now create below object in Database Class



        private static final String DATABASE_NAME = "DBName.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME="DBNAME" ;
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private String INSERT="insert into " + TABLE_NAME + " (title,type) values (?,?)";


Step 4:- Initialize object in Database class constructor 


      public Database(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}



No comments:

Post a Comment