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 :'(
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: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 bedbHelper.getWritableDatabase()
-- and the result hasn't returned for the assignment.