SQLite getReadableDatabase() returns NULL

2019-03-04 09:47发布

I'm using Android's SQLite to create a database of levels, based on some files. I first create a SQLiteOpenHelper, and on it I call getReadableDatabase() or getWritableDatabase() so the onCreate() method is called and my DB will be created:

@Override //Main Activity
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper = new DbOpenHelper(this);
    database = dbHelper.getWritableDatabase();  //is a field

-

public DbOpenHelper(Context context) {
    super(context, DB_NAME, null, DATABASE_VERSION);
    Log.d("CREATING CLASSS", "OSDIFJE*(#");
}

 @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DB_TABLE_CREATE);
    loadLevelData();
}

// Load data into the database on creation
private void loadLevelData() {
    Log.d("DbOpenHelper", "Loading Level Data");
    AssetManager mgr = MenuActi ~~snip~~                                                     
    Log.d("dataaosdifj",MenuActivity.database.toString()); //NullPointerException!
    MenuActivity.database.insert(DB_TABLE_NAME, null, info);
        }  

i Also tried calling getWritableDatabase() inside the loadLevelData() method, same results.
I saw this is quite a common problem, however most threads about it don't have any solution!

Please :'(

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-04 10:23

Why are accessing an instance variable from an activity from inside your open helper? If I understand your code correctly, your loadLevelData() method is a method of your open helper. Instead of what you have, why not this:

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DB_TABLE_CREATE);
    loadLevelData(db);
}

// Load data into the database on creation
private void loadLevelData(SQLiteDatabase db) {
    ...
    db.insert(DB_TABLE_NAME, null, info);
} 

The root of your problem is that the database instance variable in your activity isn't assigned by the time you access it down in your DbOpenHelper... you're still in the call that's creating the database -- which happens to be dbHelper.getWritableDatabase() -- and the result hasn't returned for the assignment.

查看更多
登录 后发表回答