2014-04-04 19 views
0

我與我的數據庫幫助程序類似。表格沒有被創建。 我知道這裏有幾個「數據庫沒有創建」的問題,我嘗試了他們的解決方案。 我已經檢查過,我調用了`mDbHelper.getWritableDatabase(),我試過更改表名並取消安裝重新安裝應用程序(清除應用程序數據後)。它沒有幫助。我仍然在錯誤日誌中收到相同的消息onCreate()未在數據庫幫助程序中調用

這是相關的代碼位。讓我知道如果你需要任何看到更多it.`的

public class OfflineDBCache { 

public static final String KEY_ROWID = "_id"; 
public static final String KEY_JSON_STRING = "json_string"; 




private DatabaseHelper mDbHelper; 
private static SQLiteDatabase mDb; 

/** 
* Database creation sql statement 
*/ 
private static final String DATABASE_CREATE = 
    "create table notes (_id integer primary key autoincrement, " 
    + "json_string integer not null);"; 


private static final String DATABASE_NAME = "data"; 
private static final String DATABASE_TABLE = "offlineTable"; 
private static final int DATABASE_VERSION = 1; 

private final Context mCtx; 

private static class DatabaseHelper extends SQLiteOpenHelper { 

    DatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

     db.execSQL(DATABASE_CREATE); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

     db.execSQL("DROP TABLE IF EXISTS notes"); 
     onCreate(db); 
    } 
} 

/** 
* Constructor - takes the context to allow the database to be 
* opened/created 
* 
* @param ctx the Context within which to work 
*/ 
public OfflineDBCache(Context ctx) { 
    this.mCtx = ctx; 
} 

/** 
* Open the notes database. If it cannot be opened, try to create a new 
* instance of the database. If it cannot be created, throw an exception to 
* signal the failure 
* 
* @return this (self reference, allowing this to be chained in an 
*   initialization call) 
* @throws SQLException if the database could be neither opened or created 
*/ 
public OfflineDBCache open() throws SQLException { 
    mDbHelper = new DatabaseHelper(mCtx); 
    mDb = mDbHelper.getWritableDatabase(); 
    return this; 
} 

public void close() { 
    mDbHelper.close(); 
} 

我知道是沒有得到創建表,因爲我得到這個在logcat中:

04-05 00:07:25.602: E/SQLiteLog(8568): (1) no such table: offlineTable 

回答

3

你正在創建表筆記

private static final String DATABASE_CREATE = 
    "create table notes (_id integer primary key autoincrement, " 
    + "json_string integer not null);" 

所以,你應該用注小號與其使用offlineTable

private static final String DATABASE_TABLE = "notes"; // Replaced offlineTable with notes 

更新好的做法

當你正在使用的表名不變,你可以修改你DATABASE_CREATE如下

private static final String DATABASE_CREATE = 
    "create table " + DATABASE_TABLE + "(_id integer primary key autoincrement, " 
    + "json_string integer not null);"; 

相同delete語句到onUpgare()

db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 

由於這是一個很好的方式,你也可以很容易地改變你的表名,通過改變只DATABASE_TABLE值。

+1

還應該注意的是,如果要創建最終變量,則應在適用時使用它。在這種情況下,創建語句應該是「創建表」+ DATABASE_NAME +(_id整數主鍵自動增量,json_string整數非空);「 – zgc7009

+0

謝謝,我複製粘貼從我的一箇舊應用程序的類,我太累了,意識到我是在做一些愚蠢的事情 – DrkStr

+0

@ zgc7009謝謝。更新了答案:)。 –