zono zono - 1 month ago 9
Android Question

Android SQLiteOpenHelper : onCreate() method is not called. Why?

I am trying to make my first android app. I heard that the SQLiteOpenHelper.onCreate() method process to create tables if the database is not created. 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();
}
}

=================================================================

Answer

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!

Comments