Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
429 views
Welcome To Ask or Share your Answers For Others

1 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...