Skip to content Skip to sidebar Skip to footer

Passing Context To Sqliteopenhelper

First up, I am new to android apps and am not working solo on this. My team mate has taken design while I handle this, and asked me to set up the database and the method to do this

Solution 1:

Here is what I usually do:

publicclassMyApplicationextendsApplication {
    privatestatic MyApplication  instance;
    publicMyApplication()
    {
       instance = this;
    }
    publicstatic Context getContext()
    {
       return instance;
    } 

And just set that class into the manifest

<applicationandroid:name="my.workspace.MyApplication"...
 >

After that just call MyApplication.getContext(), where you need it.

Solution 2:

If you're using eclipse it's beyond child's play. Just make a field somewhere "private Context context" then you go to generate constructor from fields in the source tab. Just spits it out for you. Then when you need to make an instance of the class. Usually "this" in parameters will suffice

EDIT


I hope this helps, I'd rather not prolong a discussion here. in your database:

publicDataBaseHelper(Context  context) {
    super(context, DB_NAME, null, 1);
}

public Cursor getDrinks() {
        SQLiteDatabasedb= getReadableDatabase();
        Cursorcursor= db.query(DB_NAME, null, null, null, null, null, null);
        return cursor;
    }

Then in your activity (in oncreate):

private Cursor c;

...
DataBaseHelperdrinksDataBase=newDataBaseHelper(this);
c = drinksDataBase.getDrinks(); 
c.moveToFirst();

Post a Comment for "Passing Context To Sqliteopenhelper"