Android SQLiteOpenHelper:为什么不调用 onCreate() 方法?

发布于 2024-11-25 12:41:06 字数 1437 浏览 5 评论 0原文

我正在尝试制作我的第一个 Android 应用程序。我注意到,如果数据库不存在,则不会调用 SQLiteOpenHelper.onCreate() 方法来创建表。然而,即使我尝试调试,onCreate() 方法也不起作用。

请查看下面的代码并给我任何建议。任何帮助将不胜感激。

public class NameToPinyinActivity extends Activity {

    DatabaseOpenHelper helper = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nametopinyin);

        Button searchButton = (Button) findViewById(R.id.search);
        searchButton.setOnClickListener(new ButtonClickListener());

        helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
    }

public class DatabaseOpenHelper extends SQLiteOpenHelper {

    /** DB Name */
    private static final String DB_NAME = "pinyin";

    /** CREATE TABLE SQL */
    private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
            + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";

    public DatabaseOpenHelper(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            db.execSQL(CREATE_TABLE_SQL);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

I am trying to make my first Android app. I noticed that the SQLiteOpenHelper.onCreate() method is not called to create tables if the database not exists. However, the onCreate() method did not work even thought I tried to debug.

Please look at the code below and give me any suggestions. Any help will be appreciated.

public class NameToPinyinActivity extends Activity {

    DatabaseOpenHelper helper = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nametopinyin);

        Button searchButton = (Button) findViewById(R.id.search);
        searchButton.setOnClickListener(new ButtonClickListener());

        helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
    }

public class DatabaseOpenHelper extends SQLiteOpenHelper {

    /** DB Name */
    private static final String DB_NAME = "pinyin";

    /** CREATE TABLE SQL */
    private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
            + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";

    public DatabaseOpenHelper(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            db.execSQL(CREATE_TABLE_SQL);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

七度光 2024-12-02 12:41:06

我在使用 SQLiteOpenHelper 时也遇到了麻烦。对我有用的是将成员变量存储

SQLiteDatabase db;

在 SQLiteOpenHelper 子类中并

 db = getWritableDatabase();

在构造函数中调用。

这个问题的答案还包括有用的信息:SQLiteOpenHelper failed to call onCreate?

我希望这有帮助!

I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable

SQLiteDatabase db;

In the SQLiteOpenHelper subclass and calling

 db = getWritableDatabase();

in the constructor.

The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?

I hope this helps!

回忆躺在深渊里 2024-12-02 12:41:06

在调用 SQLiteOpenHelper 类的 getWritableDatabase()getReadableDatabase() 方法之前,不会创建数据库。

就像当您实际需要时在内存中创建数据库一样简单。:)

Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.

as simple as that database will be created in memory when you actually need that.:)

冬天旳寂寞 2024-12-02 12:41:06

我遇到了类似的问题,onCreate 没有执行。也许这对某人有任何用处,尽管结果是一个不同的问题。

我之前正在做数据库,并且很早之前就已经创建了一个。所以现在在 onCreate() 中进行更改后,我希望找到创建的新表。但 SQLiteOpenHelper 再也没有调用过 onCreate() 。原因是,数据库已经存在。我仍然使用与以前相同的设备,因此使用已经存在的(旧的)数据库。

但还有希望。当系统发现同名数据库已存在时,它还会检查版本号是否正确。在这种情况下,我只是忘记了数据库已经存在。我的解决方案只是更改版本号。因此 onUpgrade() 被调用,为 onCreate() 更改提供选项。

因此,选项要么卸载整个应用程序(以及数据库),要么在升级版本号(例如删除)旧表并再次调用 onCreate() 后再次调用 onCreate。

无论如何,如果没有调用 onCreate(),请检查两次数据库是否存在。否则不会再次调用。

I had a similar problem where onCreate wasn't executed. Maybe this is of any use for someone even though it turned out being a different problem.

I was working on the database before and had already created one long time before. So now after making changes in onCreate() I was hoping to find the new tables created. But the SQLiteOpenHelper never called onCreate() again. Reason was, the database already existed. I was still working with the same device as before and consequently with the already existing (old) databse.

But there is hope. When the system sees a database with that name already exists, it also checks whether the version number is correct. In that case I simply forgot the database already existed. My solution was simply changing the version number. So onUpgrade() was called offering options for onCreate() changes.

So options were either uninstalling the complete app (and with it the database) or call onCreate again after upgrading the version number (and for example dropping) the old table and calling onCreate() again.

In any case, if onCreate() is not called, check twice if the database exists. Otherwise it's not called again.

段念尘 2024-12-02 12:41:06

我遇到了类似的问题,但问题不是 OnCreate 调用。

在上面的示例代码中,Kevin 解释说,如果数据库已存在,则不会调用 OnCreate。但是,如果像我一样,您正在使用来自不同活动的多个表,那么尽管您可能已经创建了数据库,但与此活动关联的表可能尚未创建。因此,当您尝试在不存在的表上设置游标数据时,您将引发异常。

我的解决方案是定义一个名为 CreateTable 的单独类,该类既可以从 OnCreate 重写调用,也可以从

db = getWritableDatabase();之后的构造函数调用

I had a similar problem however it was not the OnCreate call that was the issue.

In the example code above, Kevin explained that the OnCreate is not called if the database already exists. However if, like me, you are using multiple tables from separate activities, then though you may have created the database already, the table associated with this activity may yet have not been created. Hence when you attempt to set the cursor data on a non-existent table, you will invoke an exception.

My solution was define a separate class called CreateTable which is called both from the OnCreate override and from the constructor after the

db = getWritableDatabase();

奢欲 2024-12-02 12:41:06

调用 getWritableDatabase();在构造函数中

public DataBaseH(@Nullable Context context) {
    super(context, dataBaseName, null, dataBaseVersion);
    SQLiteDatabase db=this.getWritableDatabase();

}

@Override
public void onCreate(SQLiteDatabase db) {
 String createTable="CREATE TABLE IF NOT EXISTS "+tableName+                              " ( "+
            id+  " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
            name+                              " TEXT,"+
            familyName+                        " TEXT,"+
            age+                           " INTEGER);";

    db.execSQL(createTable);

     Log.i(TAG,"db.exect");


}

Call getWritableDatabase(); in the constructor

public DataBaseH(@Nullable Context context) {
    super(context, dataBaseName, null, dataBaseVersion);
    SQLiteDatabase db=this.getWritableDatabase();

}

@Override
public void onCreate(SQLiteDatabase db) {
 String createTable="CREATE TABLE IF NOT EXISTS "+tableName+                              " ( "+
            id+  " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
            name+                              " TEXT,"+
            familyName+                        " TEXT,"+
            age+                           " INTEGER);";

    db.execSQL(createTable);

     Log.i(TAG,"db.exect");


}
情话难免假 2024-12-02 12:41:06

我遇到了类似的问题,当应用程序第一次运行时 onCreate() 没有执行,所以我的数据库从未被创建。这与 onCreate() 由于数据库已存在而未执行时不同,因为数据库尚不存在。具体来说,我的 DataProvider onCreate() 没有执行,因此 OpenHelper 也从未被调用。

我确认我已按照每个人在之前的答案中描述的方式设置了所有内容,但没有解决我的问题。发布这个答案以防其他人像我一样忘记一个小细节。

解决我问题的方法是在 AndroidManifest.xml 中为我的数据提供程序添加一个条目,该条目与我的所有条目一起嵌套在标签内。我需要的唯一属性是:

  • android:name=".DataManagement.DbDataProvider"
  • android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
  • android:exported="false"

(确保更改上述属性的值为了匹配您的项目)

我为数据提供程序清理、构建、运行和 onCreate() 方法,并正确执行了打开帮助器类,并且在第一次应用程序启动时创建了数据库!

I was having a similar problem with onCreate() not executing when the app was very first run, so my database never got created. This is NOT the same as when onCreate() is not executing because the database already existed, because the database did not yet exist. Specifically, my DataProvider onCreate() was not executing, so the OpenHelper never got called either.

I verified I had everything set up the way that everyone described in the previous answers, but nothing resolved my problem. Posting this answer in case anyone else forgets one small detail like I did.

What resolved the problem for me was adding a entry in AndroidManifest.xml for my Data Provider, nested inside the tags, along with all of my entries. The only attributes I needed were:

  • android:name=".DataManagement.DbDataProvider"
  • android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
  • android:exported="false"

(Make sure to change the values for the above attributes to match your project)

I cleaned, built, ran, and onCreate() methods for the data provider and open helper classes executed properly, and the database was created on first application launch!

在梵高的星空下 2024-12-02 12:41:06

我遇到了同样的问题..我的解决方案是添加 .db 作为数据库名称的扩展名

I had the same problem.. the resolution for me was to add .db as extension of the database name

超可爱的懒熊 2024-12-02 12:41:06

就我而言,它没有被调用,因为数据库已经存在!因此,如果可能的话,请确保删除您的应用程序并将其重新安装,然后再检查它是否被调用。

In my case, it was not being called because the database already existed! So, if possible, make sure to delete your app and install it back and only then check if it is being called or not.

天邊彩虹 2024-12-02 12:41:06

我遇到了同样的问题,似乎 onCreate 没有执行。我这么认为是因为我的日志没有显示。结果发现我的 SQL_create String 中的空格有问题。

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
        db.execSQL(SQL_CREATE);
    }
    catch (Exception ex) {
        Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
    }
}

这是我更正后的 SQL 字符串:

enterpublic static final String SQL_CREATE =
        "CREATE TABLE " + TABLE_VOCAB_LIST +
                "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_GERMAN + " TEXT NOT NULL, " +
                COLUMN_SPANISH + " INTEGER NOT NULL, "+
                COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here

我忘记了一个空格,当我添加它时,一切正常。

I had the same problem where it seemed that the onCreate was not executed. I thought so because my logs were not displayed. Turned out that there was something wrong with the blank spaces in my SQL_create String.

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
        db.execSQL(SQL_CREATE);
    }
    catch (Exception ex) {
        Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
    }
}

This is my corrected SQL-String:

enterpublic static final String SQL_CREATE =
        "CREATE TABLE " + TABLE_VOCAB_LIST +
                "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_GERMAN + " TEXT NOT NULL, " +
                COLUMN_SPANISH + " INTEGER NOT NULL, "+
                COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here

I had forgotten one blank space and when I added it everything worked fine.

阳光下慵懒的猫 2024-12-02 12:41:06

您可以将自动增量更改为自动增量

注意
SQLiteOpenHelper 第一次创建数据库时调用onCreate。如果您在 onCreate 方法中创建表,则无法创建新的 SQLiteDatabase。你可以看例子

    @Override
    public void onCreate(SQLiteDatabase db) {
        String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
                "id TEXT PRIMARY KEY, " +
                "name TEXT )";
        db.execSQL(stringCreateTable);
    }

You can change AUTOINCREMENT to AUTO INCREMENT

Note
SQLiteOpenHelper Called onCreate when the database is created for the first time. If you create table in onCreate method you can't create new SQLiteDatabase. You can see example

    @Override
    public void onCreate(SQLiteDatabase db) {
        String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
                "id TEXT PRIMARY KEY, " +
                "name TEXT )";
        db.execSQL(stringCreateTable);
    }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文