Search code examples
androidandroid-fragmentsandroid-sqlitesqliteopenhelper

object of SQLiteOpenHelper only can be declared in onAttach and null elsewhere


i have a class that extends SQLiteOpenHelper, in the activity, i declared the variables MQTT_Settings_DB and SQLiteDatabase as shown beow in the code.

the problem is when i declared the variable MQTT_Settings_DB and initialised globally as show shown in the code, at run time, this line

this.sqliteDB = this.mqttSettingsDB.getWritableDatabase();

that exists in commitToSQLiteDB() causes the App to crash and i receive NPE, to solve this issue, i placed the declaration of the

this.mqttSettingsDB

in onAttach() as follows

onAttach() {

this.mqttSettingsDB = new MQTT_Settings_DB(getActivity());
}

the App does not crash.

why the object MQTT_Settings_DB is defined in onAttach and can not be defined globally?

code:

private MQTT_Settings_DB mqttSettingsDB = new MQTT_Settings_DB(getActivity());
private SQLiteDatabase sqliteDB = null;
....
....
....
protected boolean commitToSQLiteDB() {
    // TODO Auto-generated method stub
    if (this.mqttSettingsDB == null) {
        Log.e(TAG, "@commitToSQLiteDB(): this.mqttSettingsDB == null");
        this.mqttSettingsDB = new MQTT_Settings_DB(getActivity());
    }
    if (this.sqliteDB == null) {
        Log.e(TAG, "@commitToSQLiteDB(): this.sqliteDB == null");
        this.sqliteDB = this.mqttSettingsDB.getWritableDatabase();// always causes error??
    } else {

        if (!this.sqliteDB.isOpen()) {
            this.sqliteDB = this.mqttSettingsDB.getWritableDatabase();
        }
    }

Solution

  • private MQTT_Settings_DB mqttSettingsDB = new MQTT_Settings_DB(getActivity());
    

    getActivity() returns null before the fragment is attached to an activity. Passing null to a SQLiteOpenHelper constructor doesn't crash immediately but it will when you try to actually open the database with e.g. getWritableDatabase().