问题描述
我正在尝试制作我的第一款Android应用。我注意到,如果数据库不存在,则不会调用 SQLiteOpenHelper.onCreate()
方法来创建表。但是,即使我试图调试, onCreate()
方法也不起作用。
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();
}
}
推荐答案
我也有 SQLiteOpenHelper 的问题。对我有用的是存储成员变量
I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable
SQLiteDatabase db;
在SQLiteOpenHelper子类中并调用
In the SQLiteOpenHelper subclass and calling
db = getWritableDatabase();
在构造函数中。
答案这个问题还包括有用的信息:
The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?
我希望这有帮助!
这篇关于Android SQLiteOpenHelper:为什么不调用onCreate()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!