How to Create DataBase in Android
Create a new project in Android Studio
File – New Android Project
Using of DataBaseHelper Class
Once the projected is created create a new class in your project src directory and name it as DataBaseHendler.java(Right click on src/package – New – Class)
Now extend your DatabaseHandler.java class from SQLiteOpenHelper.
public class DataBaseHendler extends SqLiteOpenHelper {
After extends your class from SqLiteOpenHelper you need to override two method onCreate() and onUpgrade.
onCreate():-These is where we need to write create table statements. This is called when database is created.
onUpgrade():-This method is called when database is upgraded like modifying the table structure, adding constraints to database .
Create DataBaseHelper Class
Right click on package Name – New – Java Class
For Ex:-
public class DataBaseHelper extends SQLiteOpenHelper { // Database version name private static final int DATABASE_VERSION = 1; // Database name private static final String DATBASE_NAME = "regForm.db"; public static final String TABLE_NAME = "user"; public static final String USER_ID = "_id"; public static final String NAME = "name"; public static final String EMAIL = "email"; public DataBaseHelper(Context context) { super(context, DATBASE_NAME, null, DATABASE_VERSION); } //Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_USER_TABLE = "create table " + TABLE_NAME + " ( " + USER_ID + " integer primary key autoincrement," + NAME + " TEXT," + EMAIL + " TEXT," db.execSQL(CREATE_USER_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Inserting new Record in the Table
To Insert a new Record in Table we need to create an Object of ContentValues class and put the Values in this like:
// Assign value for each row ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); // Contact Name values.put(KEY_PH_NO, contact.getAddress()); // Contact Address // Insert the row into your table db.insert(TABLE_CONTACTS, null, values); db.close(); // Closing database connection }
Reading Row
For Ex:
Deleting Record
deleteContact() will delete single contact from database. deleteContact() public void deleteContact(Contact contact){ SqLiteDatabase db=this.getWriteableDatabase(); Db.delete(TABLE_CONTACTS, KEY_ID + “ ?”, new String [] { String.valueof(contact.getid)}); Db.close(); }