Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Created April 25, 2014 19:22
Show Gist options
  • Save sketchpunk/11300225 to your computer and use it in GitHub Desktop.
Save sketchpunk/11300225 to your computer and use it in GitHub Desktop.
SqliteOpenHelper class setup using a singleton pattern with the application context. It also loads in an sql file from the assets folder when its needs to create a database. Mucher easier way to create a new db this way instead of hardcoding all the sql into string.
CREATE TABLE IF NOT EXISTS TableOne(
id INT PRIMARY KEY NOT NULL
,title VARCHAR(20) NULL
);
CREATE TABLE IF NOT EXISTS TableTwo(
id INT PRIMARY KEY NOT NULL
,title VARCHAR(20) NULL
);
package com.sketchpunk;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.util.Scanner;
public class MainDBHelper extends SQLiteOpenHelper{
public static final String DB_NAME = "main.db";
public static final int DB_VERSION = 1;
private Context mContext;
//===========================================================
//Singleton Pattern
private static MainDBHelper mInstance = null;
public static MainDBHelper get(Context context){
if(mInstance == null) mInstance = new MainDBHelper(context.getApplicationContext());
return mInstance;
}//func
//===========================================================
//
public MainDBHelper(Context context){
super(context,DB_NAME,null,DB_VERSION);
mContext = context;
}//const
@Override
public void onCreate(SQLiteDatabase db){
Scanner scan = null;
db.beginTransaction();
try{
scan = new Scanner(mContext.getAssets().open("main.sql"));
scan.useDelimiter(";");
while(scan.hasNext()) db.execSQL(scan.next());
db.setTransactionSuccessful();
}catch(IOException e){
e.printStackTrace();
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}finally{
if(scan != null) scan.close();
}//if
db.endTransaction();
}//func
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion){
/*
for(int i=oldVersion+1; i <= newVersion; i++){
switch(i){
case 2:
db.execSQL("ALTER TABLE TableTwo ADD COLUMN something VARCHAR(300) NULL;");
break;
}//if
}//for
*/
}//func
}//cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment