SQLiteOpenHelper not calling onCreate

蓝咒 提交于 2019-12-07 20:26:42

问题


This is the fist time I've used SQLiteOpenHelper (or databases on android). When I get a writeable database I was wondering why onCreate isnt being called on each new instance of the class. Am I doing something wrong?

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "MyDatabase.db";
    private static final int DATABASE_VERSION = 1;
    private String PrSQLcmd = "";


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


@Override
public void onCreate(SQLiteDatabase db) 
{
    db.execSQL("CREATE TABLE IF NOT EXISTS Contact(Firstname TEXT, LastName TEXT");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}


回答1:


In SQLiteOpenHelper, the meaning of 'onCreate' is different from what it is in an Activity. Here,'onCreate' is called only once, which is the first time you create the database. The next time you run the app, the database is already there, so it won't call 'onCreate'. Your object level initialization should be done in the constructor and not in 'onCreate'

To see 'onCreate' being called, either manually delete the db file, or simply uninstall the app.



来源:https://stackoverflow.com/questions/7164303/sqliteopenhelper-not-calling-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!