android-sqlite - isOpen returns SQLiteOpenHelper 中的 nullpointerexception

android-sqlite - isOpen returns nullpointerexception in SQLiteOpenHelper

这是我的数据库类:

public class OpenHelper extends SQLiteOpenHelper {
Context context;

public OpenHelper(Context context) {
    super(context, TABLE_NAME, null, VERSION);
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    // Category table create query
    ........
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
public DatabaseHandler open() {
        helper = new OpenHelper(context);
        myDB = helper.getWritableDatabase();
        return this;
    }

    public void close() {
        myDB.close();
    }

    public boolean isOpen() {
        if(myDB.isOpen()) return true ; else return false; 
    }

}

我拥有的每个函数都可以正常工作,例如插入和更新,但是当我想检查数据库是否打开时,它崩溃了。我在 activity 中这样称呼它:

DatabaseHandler mydb=new DatabaseHandler(context);
            if(!mydb.isOpen())
                mydb.open();

这条线一直报错:

if(!mydb.isOpen())

它 returns 一个 nullpointerexception 我不知道为什么。

您在 open() 之前调用 isOpen(),您在 isOpen() 中使用的 mydb 仅在 open() 中初始化。

作为快速修复,更改

if(myDB.isOpen())

类似于

if(myDb != null && myDB.isOpen())