onCreate()没有在数据库助手中调用

时间:2014-04-04 18:47:35

标签: android android-sqlite

我正在使用我的数据库帮助程序类。表未创建。 我知道有几个"数据库没有被创建"问题在这里,我尝试了他们的解决方案。 我已经检查过我调用了`mDbHelper.getWritableDatabase(),我尝试更改表名并卸载重新安装应用程序(清除应用程序数据后)。它没有帮助。我仍然在错误日志

中收到相同的消息

以下是相关的代码位。如果你需要再看到它,请告诉我。

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

1 个答案:

答案 0 :(得分: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);";

与onUpgare()

中的删除语句相同
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

这是一种很好的方式,您也可以通过仅更改DATABASE_TABLE的值来轻松更改您的表名。