Skip to content Skip to sidebar Skip to footer

GetDatabase Called Recursively

My first time asking a question here, so be gentle, Lol. Anyway. Ive been working on an Android and my latest build ran flawlessly.. Until yesterday, when IT gave me a new workst

Solution 1:

Try changing your setDefaultLabel() method to...

public void setDefaultLabel(SQLiteDatabase db)

...then in onCreate(...) simply pass the db parameter into it and get rid of this line...

SQLiteDatabase db = this.getWritableDatabase();

Your code should then look like this...

@Override
public void onCreate(SQLiteDatabase db) {
    // Create tables        
    db.execSQL(CREATE_CATEGORIES_TABLE);        
    db.execSQL(CREATE_CHRGDATA_TABLE);
    db.execSQL(CREATE_SETTINGS_TABLE);
    setDefaultLabel(db);
}

/**
 * 
 */

public void setDefaultLabel(SQLiteDatabase db) {
    // create default label
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, "Default");
    db.insert(TABLE_LABELS, null, values);
}

The problem in your existing code is that onCreate(...) is being passed a reference to the open / writeable database but it then calls setDefaultLabel(...) which attempts to get another writeable reference to the database.


Solution 2:

Here is my solution for this: In the Helper, I override 2 methods getWritableDatabase() and getReadableDatabase() like below: Notice that you should not close the database, it may be crashed.

    @Override
    public void onCreate(SQLiteDatabase db) {
        // All your code here .....

        // Add default value for all tables
        isCreating = true;
        currentDB = db;
        generateAllDefaultData();
        // release var
        isCreating = false;
        currentDB = null;
    }

    boolean isCreating = false;
    SQLiteDatabase currentDB = null;

    @Override
    public SQLiteDatabase getWritableDatabase() {
        // TODO Auto-generated method stub
        if(isCreating && currentDB != null){
            return currentDB;
        }
        return super.getWritableDatabase();
    }

    @Override
    public SQLiteDatabase getReadableDatabase() {
        // TODO Auto-generated method stub
        if(isCreating && currentDB != null){
            return currentDB;
        }
        return super.getReadableDatabase();
    }

Post a Comment for "GetDatabase Called Recursively"