2014-02-26 55 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