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

查看:659
本文介绍了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);
        }  

我也打过电话getWritableDatabase()的loadLevelData()方法内,相同的结果。结果
我看到这是一个相当普遍的问题,但是关于它的多数线程没有任何的解决方案!

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!

请:(

推荐答案

为什么从开启辅助访问内从活动的一个实​​例变量?如果我没有理解你的code,你的 loadLevelData()方法是打开的辅助方法。相反,你有什么,为什么不这样:

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时分配......你依然在呼叫的创建数据库 - 这恰好是 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天全站免登陆