package com.minich.sqldemo1; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper{ public SQLiteDatabase DB; public String DBPath; public static String DBName = "sample"; public static final int version = '1'; public static Context currentContext; public static String tableName = "Students"; public DBHelper(Context context) { super(context, DBName, null, version); currentContext = context; DBPath = "/data/data/" + context.getPackageName() + "/databases"; createDatabase(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private void createDatabase() { boolean dbExists = checkDbExists(); if (dbExists) { // do nothing } else { DB = currentContext.openOrCreateDatabase(DBName, 0, null); DB.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + " (lastName VARCHAR, firstName VARCHAR," + " school VARCHAR, age INT(3));"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Doe','John','Wyo',16);"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Smith','Jane','Wilson',17);"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Rodriguez','Nate','Mifflin',18);"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Watkins','Andrea','Berks Catholic',14);"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Miller','Emily','Wyo',15);"); DB.execSQL("INSERT INTO " + tableName + " VALUES ('Sampson','Bill','Wyo',16);"); } } // check to see if this database already exists in this package private boolean checkDbExists() { SQLiteDatabase checkDB = null; try { String myPath = DBPath + DBName; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database does't exist yet. } if (checkDB != null) { checkDB.close(); } if (checkDB != null) { return true; } else { return false; } } }