SQLiteOpenHelper 不调用 onCreate
这是我第一次使用 SQLiteOpenHelper(或 android 上的数据库)。当我获得一个可写数据库时,我想知道为什么 onCreate 没有在该类的每个新实例上被调用。我做错了什么吗?
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 SQLiteOpenHelper 中,“onCreate”的含义与 Activity 中的含义不同。这里,'onCreate'仅被调用一次,这是第一次创建数据库。下次运行应用程序时,数据库已经存在,因此它不会调用“onCreate”。您的对象级初始化应该在构造函数中完成,而不是在“onCreate”中完成。
要查看“onCreate”被调用,请手动删除 db 文件,或者干脆卸载应用程序。
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.