1. Add a static method in SomeClass that tells it what Context to use:

2. In this method, call context.getApplicationContext() and keep the result. Do not keep a reference to the context that's passed it (so you are not referencing an Activity after it's been destroyed by Android).

public static void setContext(Context context) {
gContext = context.getApplicationContext();
}

private static Context gContext;

3. Call setContext() from some place you have one (such as Activity).

-- Kostya

30.12.2010 14:43, svebee пишет:
I have some class (SomeClass.class). I want to have some static
methods in it like getAllDatabaseItems, getTableItems, insertNewRecord
and so on.

If I do it this way

         SQLiteDatabase db = openOrCreateDatabase(DATABASE_NAME,
MODE_PRIVATE, null);

I need to extend Activity (but still can't use it in static methods)
or pass a "db" variable in every single method (from "caller
activity") which is pretty bulky.

What's the solution so I can from some class call
SomeClass.getAllDatabaseItems()? In short I have two classes, I have
main activity/class (which displays UI and so on) and
DatabaseOptions.java class which I should call anytime I need to (from
any other activities as well) to manipulate with my database.

User @MobileDev123 suggested me to use Context but I'm still not
getting it right...even this code isn't working.

public class Partner extends Activity {
@SuppressWarnings("static-access")
public Partner(Context mContext) {
     myContext = mContext;
     db = openOrCreateDatabase(DATABASE_NAME, myContext.MODE_PRIVATE,
null);

     db.execSQL("CREATE TABLE IF NOT EXISTS " + PARTNER_TABLE_NAME +
" (id INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR);");
     db.execSQL("CREATE TABLE IF NOT EXISTS " + ADDRESS_TABLE_NAME +
" (id INTEGER PRIMARY KEY AUTOINCREMENT, " + PARTNER_ID + " INT, " +
ADDRESS + " VARCHAR, " + CITY + " VARCHAR);");
}

And then call it from some of my activites like this

     Partner newPartner = new Partner(this);
     partnersItems = newPartner.getAllItems();

I get an NullExceptionError on line 4 (Partner.class) - why? If I use
static reference on

MODE_PRIVATE -->  (Context.MODE_PRIVATE)

again it's not working.



--
Kostya Vasilyev -- WiFi Manager + pretty widget -- http://kmansoft.wordpress.com

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to