【问题标题】:SQLiteOpenHelper "onCreate" is not called? (the DB does not exist)SQLiteOpenHelper“onCreate”没有被调用? (数据库不存在)
【发布时间】:2012-04-13 20:29:00
【问题描述】:

从我以这种方式实例化的片段

fmdata = new FileManagerData(getActivity());

以下课程。我不明白为什么没有调用 onCreate() 并且没有创建我的数据库。

public class FileManagerData {
public static final String TAG = FileManagerData.class.getSimpleName();;


Context context;
DBHelper dbHelper;

public FileManagerData (Context context){
    this.context = context;
    dbHelper = new DBHelper();
}

private class DBHelper extends SQLiteOpenHelper{

    private static final String DB_NAME = "filename.db";
    private static final String DB_SQL = "filename.sql";
    private static final int DB_VERSION = 1; // internal number

    public DBHelper() {
        super(context, DB_NAME, null, DB_VERSION);  
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            // this is NEVER called and my DB does not exist yet
    }

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

    }   
}

编辑:诀窍是必须使用数据库(读取或写入),因此调用 onCreate()。

【问题讨论】:

  • 必须先打开/使用 DBHelper 吗?
  • 这是一个很好的提示,请将其标记为答案,以便我接受并点赞

标签: android sqlite sqliteopenhelper


【解决方案1】:

onCreate 方法将在首次访问数据库后调用。查询数据库,onCreate 将被调用。

【讨论】:

    【解决方案2】:

    该数据库可能存在于较早的尝试中。

    卸载您的应用,然后重试。

    【讨论】:

      【解决方案3】:

      你应该把 onCreate 这个:

      sqLiteDatabase.execSQL("create table" + DB_NAME + " ( _id integer primary key autoincrement, " + fieldOne + "INTEGER, " + fieldTwo + "INTEGER);");
      

      其中 fieldOne 和 fieldTwo 是表格列的名称。也看这里: http://www.sqlite.org/datatype3.html

      【讨论】:

        【解决方案4】:

        我知道这个帖子已经接受了答案。尽管如此,这是我必须补充的:

        我有:

            protected class OpenHelper extends SQLiteOpenHelper {
        
            @Override
            public void onCreate(SQLiteDatabase db) {
                try {
                     MHSqlDb.this.createTables(db);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        

        我这样称呼:

            iOpenHelper = new OpenHelper(iDbFileName, DATABASE_VERSION );
        

        数据库文件在这个阶段不存在。

        然后我对应用程序进行一些调试。 我从不打电话

            iOpenHelper.getReadableDatabase();
        

        我没有打电话

            iOpenHelper.getWritableDatabase();
        

        数据库文件仍然不存在。现在,当我从调试器中终止应用程序时,我突然可以看到创建的数据库文件(名称在 iDbFileName 中)。从不调用 OpenHelper 的 onCreate 方法。

        因此,虽然我同意 onCreate 方法的意图似乎是在数据库文件不存在并且调用 getReadableDatabase() 或 getWritableDatabase() 时调用,但显然并非总是如此。

        【讨论】:

          【解决方案5】:

          卸载应用程序将删除数据库,因此将在下次运行时调用 onCreate。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-19
            • 2011-06-28
            • 1970-01-01
            • 2013-03-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多