Last active
December 16, 2015 16:49
-
-
Save leonguyen/5465834 to your computer and use it in GitHub Desktop.
Android Lab: External with SQLite - Create Database class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.example.androidlab; | |
| import java.io.File; | |
| import android.content.Context; | |
| import android.database.sqlite.SQLiteDatabase; | |
| import android.database.sqlite.SQLiteDatabase.CursorFactory; | |
| import android.database.sqlite.SQLiteOpenHelper; | |
| import android.os.Environment; | |
| import android.util.Log; | |
| public class UserDA extends SQLiteOpenHelper { | |
| // All Static variables | |
| // Database | |
| private static final String DB_NAME = "user.db"; | |
| private static final int DB_VERSION = 1; | |
| private static final String DB_PATH = "User"; | |
| public static String DB_DIR = null; | |
| public static String DB_FULL_PATH = null; | |
| static { | |
| File root = Environment.getExternalStorageDirectory(); | |
| if (root != null && root.canWrite()){ | |
| DB_DIR = root.getAbsolutePath() + File.separator + DB_PATH; | |
| File dir = new File(DB_DIR); | |
| dir.mkdirs(); | |
| } | |
| DB_FULL_PATH = DB_DIR + File.separator + DB_NAME; | |
| } | |
| // Table name | |
| private static final String TABLE_NAME = "user"; | |
| // Table Columns names | |
| private static final String KEY_ID = "id"; | |
| private static final String KEY_NAME = "name"; | |
| public UserDA(Context context) { | |
| super(context, DB_FULL_PATH, null, DB_VERSION); | |
| } | |
| public UserDA(Context context, String name, CursorFactory factory, | |
| int version) { | |
| super(context, name, factory, version); | |
| // TODO Auto-generated constructor stub | |
| } | |
| @Override | |
| public void onCreate(SQLiteDatabase db) { | |
| // TODO Auto-generated method stub | |
| String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "(" | |
| + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + ")"; | |
| db.execSQL(CREATE_CONTACTS_TABLE); | |
| Log.d("User", "DB created!"); | |
| } | |
| @Override | |
| public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | |
| // TODO Auto-generated method stub | |
| // Drop older table if existed | |
| db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); | |
| // Create tables again | |
| onCreate(db); | |
| Log.d("User", "DB upgraded!"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment