How To Refer To To A Sqlite Database From An 'independent' Method In Android
Solution 1:
Rather than having your database class extend Activity, you should pass the relevant Context to the class. You can pass it in the constructor and keep a reference to the Context as a class variable.
publicclassBarCode {
privatefinal Context mContext;
publicBarCode(Context context) {
mContext = context;
}
publicvoidinsertBarCode(String upc) {
SQLiteDatabase db;
db = mContext.openOrCreateDatabase(
"StockControl.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
ContentValuesmUpc=newContentValues();
mUpc.put("upc", "444");
mUpc.put("description", "Box o toast");
mUpc.put("scan_count", "1");
db.insertOrThrow("tbl_upc", null, mUpc);
}
}
To use the class, you would do this in your Activity:
BarCodebarCode=newBarCode(this);
barCode.insertBarCode("123456");
Solution 2:
It seems the way to go about these things is to create a data helper. I followed this tutorial and now I can reference the database code from anywhere: http://www.screaming-penguin.com/node/7742
Edit: I found a much better tutorial, in fact, an excellent one from Google themselves that contains a number of best practices for doing this kind of thing including using a data adaptor to properly abstract database access. This is the Notebook Tutorial here: http://developer.android.com/resources/tutorials/notepad/index.html
Solution 3:
You can try passing the DB pointer to your mUpc routine.
mUpc.put(db,"upc","444");
You will have to rewrite the constructor of mUpc to accept the db object.
Post a Comment for "How To Refer To To A Sqlite Database From An 'independent' Method In Android"