2014-02-26 61 views
0

我用下面的代碼在我的活動,這將檢查數據庫錯誤和工作得很好:Helper類不起作用

//DB Test 
     Boolean databaseError = false; 
     SQLiteDatabase myDB = null; 
     myDB = this.openOrCreateDatabase("myDB", 0, null);   
     try { 
      myDB.rawQuery("SELECT _id FROM occasions;", null); 
      myDB.rawQuery("SELECT _id FROM instrumentations;", null); 
      myDB.rawQuery("SELECT _id FROM editions;", null); 
      myDB.rawQuery("SELECT _id FROM composers;", null); 
      myDB.rawQuery("SELECT _id FROM compositions;", null); 
     } catch (SQLiteException e) { 
      Log.e("SQLiteException", "SQLiteException"); 
      databaseError = true;  
     } 
     myDB.close(); 

我希望把代碼中的以下輔助類:

public abstract class BackupHelper { 

public static boolean checkDB() { 
    Boolean databaseError = false; 
    SQLiteDatabase myDB = null; 
    myDB = SQLiteDatabase.openDatabase("myDB", null, SQLiteDatabase.OPEN_READWRITE);   
    try { 
     myDB.rawQuery("SELECT _id FROM occasions;", null); 
     myDB.rawQuery("SELECT _id FROM instrumentations;", null); 
     myDB.rawQuery("SELECT _id FROM editions;", null); 
     myDB.rawQuery("SELECT _id FROM composers;", null); 
     myDB.rawQuery("SELECT _id FROM compositions;", null); 
    } catch (SQLiteException e) { 
     Log.e("SQLiteException", "SQLiteException"); 
     databaseError = true;  
    } 
    myDB.close(); 
    return databaseError; 
} 

}

但是,這將引發以下錯誤:

02-26 21:13:16.397: E/MyTestDatabase(29244): sqlite3_open_v2("myDB", &handle, 2, NULL) failed 02-26 21:13:17.048: E/AndroidRuntime(29244): Caused by: android.database.sqlite.SQLiteException: unable to open database file

回答

0

您必須在嘗試打開數據庫之前創建數據庫。

創建擴展SQLiteOpenHelper

public class DBCreator extends SQLiteOpenHelper { 

    // region Properties 

    private final static String tag = "DBCreator"; 

    // endregion 

    // region Constructors 

    public DBCreator(String name, int version) { 
     super(ABApplication.getContext(), name, null, version); 
    } 

    public DBCreator(Context context, String name, CursorFactory factory, 
      int version) { 
     super(context, name, factory, version); 
    } 

    public DBCreator(Context context, String name, CursorFactory factory, 
      int version, DatabaseErrorHandler errorHandler) { 
     super(context, name, factory, version, errorHandler); 
    } 

    // endregion 

    // region Overrides 
    @Override 
    public void onCreate(SQLiteDatabase db) { 

     // Execute your CREATE Table script 
    } 

    // endregion 

} 

然後你就可以通過這種方式獲取一個SQLiteDatabase實例類:

SQLiteDatabase SQLiteDatabase = new DBCreator(context, dbName, null, 1) getWritableDatabase(); 
+0

謝謝。我已經有了一個擴展sqliteopenhelper的類,但沒有使用它;-)現在它可以工作。 – Cellist