tags:

views:

61

answers:

1

Hi,

I have a DBHandler class that will be used in several activities to do some crud operations. created a MyApp class (extends Application) to hold one instantiation of the DBHandler.

My DBHandler class needs a Context to create the SQLiteOpenHelper to populate the db, etc.

That's where the problem starts: in my MyApp constructor, I want to instantiate my DBHandler, so I wrote this:

public MyApp() {
    super();
    dbh = DBHandler(<WHAT DO I PASS HERE>);
}

I tried getApplicationContext(), getBaseContext(), 'this'... nothing seems to be a fully-instantiated context at this point. I get a NPE when the SQLiteOpenHelper tries ctx.getResources().

A workaround: create the DBHandler and set it in the onCreate of my main class. -> UGLY (call me a aesthetician)

Question: is there a way to do it when Android creates MyApp?

Thanks!

+1  A: 

Creating your DBHandler in MyApp.onCreate() is the proper way to do what you want.

@Override
public void onCreate() {
    super.onCreate();
    dbh = new DBHandler(this);
}
Jere.Jones
Thanks for the confirmation. One question, though: how do I reference a Resource (or a Context) there? When I inspect the context in MyApp.onCreate(), it has a NULL mBase var. When I get to my MainActivity, that object is NO LONGER null. So it seems to me that Android is doing stuff AFTER the call to onCreate to "finish creating" the context, so during onCreate I don't have a "fully grown up context". Makes sense? I'm not sure if my supposition is true, but it definitely fails when I try to use my DBHandler, because the mBase is null. Egg and chicken problem, here?Thanks!
llappall
MyApp *IS* a Context so inside of MyApp.onCreate, whenever you need a context, pass it **this**.
Jere.Jones
Also, make sure your first line in MyApp.onCreate() is super.onCreate();
Jere.Jones