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

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - Cannot open SQLite database from SQLIte Helper Oncreate, when OnCreate is triggered by opening database for the first time

When the mainactivity tries to open the database for the first time after the app is installed, the SQLiteHelper Oncreate method is triggered (as one would expect). I want to then populate the database after the datatables are created in OnCreate, but doing so requires me to open the database again in my content creator class (which is called from OnCreate). The app crashes when it tries to open the database in the content creator class

Basically I'm trying to populate the database once it is created, but apparently not going about it the right way.

From the SQLiteHelper Class:

...

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(SQL_CREATE_TABLE); //sql string to create the table

    dbContents.baseContents(sqcontext);

}

From the content creator class:

public class dbContents {


public static void baseContents(Context context) {

    dbDataSource ds = new dbDataSource(context);
    ds.open();

...

From dbDataSource Class:

public dbDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
    DatabaseVersion = dbHelper.DatabaseVersion;  //used when MainActivity onResume to know if it needs to repopulate reminders
}

public void open() throws SQLException {
    database = dbHelper.getWritableDatabase(); //crashes here
}

...

It appears to crash at the line database = dbHelper.getWritableDatabase(); in the open() method. To reiterate, SQLiteHelper OnCreate is called when the database is opened in the main activity. When the database is opened in the mainactivity, it is calling the same open() method posted above where it is crashing when called from the dbcontents class. Is this a threading issue?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should not attempt to call getWritableDatabase() or getReadableDatabase() from SQLiteOpenHelper lifecycle methods such as onCreate() or methods called from there. That will fail with a "called recursively" exception.

Instead, use the SQLiteDatabase that is given as a parameter to onCreate() or other lifecycle methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...