I am creating a java class that DOES NOT extends Activity, and in its constructor, I want to instantiate an object from another class that instantiate SQLiteOpenHelper
. The problem is, when instantiating an object of the SQLiteOpenHelper
class I need to pass a Context
of the current class that DOES NOT extend Activity. What argument should I pass to an instance of the SQLiteOpenHelper
.
Constructor of SQLiteOpenHelper:
public class MPLDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "MPL.db";
private static final String MPL_TABLE_NAME = "MPLData";
public MPLDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Class that instantiate SQLiteOpenHelper: This is a NON_ACTIVITY Class
public class NotifyArrayAdapter {
private MPLDataBase mplOpenHelperDB = null;
private SQLiteDatabase sqliteDB = null;
private int itemClickedPos;
public NotifyArrayAdapter() {
mplOpenHelperDB = new MPLDataBase(WHAT_SHOULD_I_PASS_HERE);
}
NotifyArrayAdapterClass
public class NotifyArrayAdapter {
private MPLDataBase mplOpenHelperDB = null;
private SQLiteDatabase sqliteDB = null;
private int itemClickedPos;
public NotifyArrayAdapter(Context context) {
if (this.mplOpenHelperDB == null) {
this.mplOpenHelperDB = new MPLDataBase(context);
}
if (this.sqliteDB == null) {
this.sqliteDB = mplOpenHelperDB.getWritableDatabase();
}
}
public void deleteAtPos(int pos) {
if(! this.sqliteDB.isOpen()) {
this.sqliteDB = mplOpenHelperDB.getWritableDatabase();
}
this.itemClickedPos = pos;
int [] dbIDs = this.mplOpenHelperDB.getIDs();
mplOpenHelperDB.deleteRow(dbIDs[this.itemClickedPos]);
}
public void deleteAllDBRows() {
if(! this.sqliteDB.isOpen()) {
this.sqliteDB = mplOpenHelperDB.getWritableDatabase();
}
mplOpenHelperDB.deleteALLRows();
}
}
You need to pass current context
to your MPLDataBase
constructor
public NotifyArrayAdapter(Context con) {
mplOpenHelperDB = new MPLDataBase(con);
}
like if you call this from any Activity
then
NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(yourActivity.This);
like if you call this from any Fargment
then
NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(getActivity());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.