SQLite getReadableDatabase() 返回 NULL [英] SQLite getReadableDatabase() returns NULL

查看:56
本文介绍了SQLite getReadableDatabase() 返回 NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Android 的 SQLite 根据一些文件创建关卡数据库.我首先创建一个 SQLiteOpenHelper,然后在它上面调用 getReadableDatabase() 或 getWritableDatabase() 以便调用 onCreate() 方法并创建我的数据库:

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);
        }  

我还尝试在 loadLevelData() 方法中调用 getWritableDatabase(),结果相同.
我看到这是一个很常见的问题,但是关于它的大多数线程都没有任何解决方案!

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!

请:'(

推荐答案

为什么要从 open helper 内部的 Activity 访问实例变量?如果我正确理解你的代码,你的 loadLevelData() 方法是你的 open helper 的一个方法.除了你拥有的,为什么不这样做:

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);
} 

问题的根源在于,当您在 DbOpenHelper 中访问它时,您的活动中的 database 实例变量尚未分配......您仍在创建的调用中数据库 -- 恰好是 dbHelper.getWritableDatabase() -- 并且结果还没有为分配返回.

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.

这篇关于SQLite getReadableDatabase() 返回 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆