android 建數據庫 SQLite 存儲sd 卡或者內存
android 創建數據庫調用SQLiteOpenHelper,一般不直接操作SQLiteDatabase 。
是通過SQLiteOpenHelper來獲取
public class DBOpenHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;// 定義數據庫版本private static final String PATH = Environment
.getExternalStorageDirectory().getPath();
// 有些沒有sd卡所以沒寫進去
private final static String TAG = "DBOpen";
public DBOpenHelper(Context context) {// 定義構造函數
super(context, DBNAME, null,VERSION);// 重寫基類的構造函數
}
// 當第一次創建數據庫時回調該方法
@Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
try {
// 創建實時數據表
db.execSQL("create table alarm(sensorname integer primary key autoincrement,uid ,code ,alarmMessage ,timeCreated,boxuid)");
Log.i(TAG, "初始化數據庫");
// 初始化實時數據表
db.execSQL("insert into alarm(uid,code,alarmMessage,timeCreated,boxuid)values(‘0‘,‘0‘,‘0‘,‘0‘,‘0‘)");
} finally {
db.endTransaction();
}
}
// 當數據庫版本號更新時回調該方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)// 覆寫基類的onUpgrade方法,以便數據庫版本號更新
{
// oldVersion=舊的資料庫版本號。newVersion=新的資料庫版本號
db.execSQL("DROP TABLE IF EXISTS " + DBNAME); // 刪除舊有的資料表
onCreate(db);
}
public boolean deleteDatabase(Context context) {
return context.deleteDatabase(DBNAME);
}
這個類以下有數據庫創建,相對路徑是直接存儲在本程序的database以下。假設用絕對路徑,就能夠自選。是否sd卡。
在用到的類裏面
private DBOpenHelper helper;// 創建DBOpenHelper對象
private SQLiteDatabase db;// 創建SQLiteDatabase對象
{
helper = new DBOpenHelper(context);// 初始化DBOpenHelper對象
db = helper.getReadableDatabase();// 初始化SQLiteDatabase對象
}
直接用getReadableDatabase來獲取數據庫SQLiteDatabase對象。
這裏講一下怎麽自己主動選擇有sd卡就存在sd卡,沒有就存儲在內存中。
public DBOpenHelper(Context context) {// 定義構造函數
super(context, DBNAME, null,VERSION);// 重寫基類的構造函數
}
這個構造函數改完
public DBOpenHelper(Context context,String name) {// 定義構造函數
super(context, name, null,VERSION);// 重寫基類的構造函數
}
然後在用到的activity裏面推斷
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
name=Environment.getExternalStorageDirectory().getPath()+“/”+“alarm.db”;
}else{
name="alarm.db";
}
然後調用
helper = new DBOpenHelper(context。name);// 初始化DBOpenHelper對象
就能夠自己主動推斷了
android 建數據庫 SQLite 存儲sd 卡或者內存