我真的不知道你在哪裏使用共同的SQLiteOpenHelper
掙扎。你只需要重複你爲一張桌子做的事情!創建一個自定義的類,擴展SQLiteOpenHelper
並進行重複。
public class SQLiteCustomBase extends SQLiteOpenHelper {
private static final String CREATE_BDD_1 = "CREATE TABLE ...";
private static final String CREATE_BDD_2 = "CREATE TABLE ...";
public SQLiteCustomBase(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BDD_1);
db.execSQL(CREATE_BDD_2);
}
@Override
public void onOpen(SQLiteDatabase db) {}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE " + Vars.TABLE_1 + ";");
db.execSQL("DROP TABLE " + Vars.TABLE_2 + ";");
onCreate(db);
}
}
,然後在你執行一些數據庫操作的類:
public class HandlerClass {
private SQLiteDatabase db;
private SQLiteCustomBase customBase;
public HandlerClass(Context context){
customBase = new SQLiteCustomBase(context, Vars.NAME_DB, null, Vars.VERSION_DB);
}
public void open(){
db = customBase.getWritableDatabase();
}
public void openForRead(){
db = customBase.getReadableDatabase();
}
public void close(){
db.close();
}
public SQLiteDatabase getDB(){
return db;
}
}
void myMethods()
{
bdd.insert(Vars.TABLE_1, null, values);
bdd.insert(Vars.TABLE_2, null, values);
}
etc.
謝謝。我還使'SQLiteCustomBase'類成爲單例,以便所有HandlerClass在整個應用程序中使用同一個'SQLiteDatabase'實例。這可以避免同時執行過程中的任何崩潰! – gauravsapiens