SQLiteOpenHelper 的对象只能在 onAttach 中声明,其他地方为 null

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

我有一个扩展 SQLiteOpenHelper 的 class,在 activity 中,我声明了变量 MQTT_Settings_DBSQLiteDatabase,如下面的代码所示.

问题是当我声明变量 MQTT_Settings_DB 并如代码所示全局初始化时,在 运行 时间,这一行

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

存在于 commitToSQLiteDB() 导致应用程序崩溃,我收到 NPE,为了解决这个问题,我放置了

的声明
this.mqttSettingsDB

onAttach()如下

onAttach() {

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

应用程序不会崩溃。

为什么对象MQTT_Settings_DB定义在onAttach中,不能全局定义?

代码:

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();
        }
    }
private MQTT_Settings_DB mqttSettingsDB = new MQTT_Settings_DB(getActivity());

getActivity() returns null 在片段附加到 activity 之前。将 null 传递给 SQLiteOpenHelper 构造函数不会立即崩溃,但是当您尝试使用例如实际打开数据库时它会崩溃。 getWritableDatabase().