我正在创建一个不扩展Activity的java类,在其构造函数中,我想从另一个实例化SQLiteOpenHelper
的类中实例化一个对象。问题是,当实例化SQLiteOpenHelper
类的对象时,我需要传递当前类的Context
,该类不会扩展Activity。我应该将什么参数传递给SQLiteOpenHelper
。
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);
}
实例化SQLiteOpenHelper的类: 这是一个NON_ACTIVITY类
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();
}
}
答案 0 :(得分:4)
您需要将当前context
传递给MPLDataBase
构造函数
public NotifyArrayAdapter(Context con) {
mplOpenHelperDB = new MPLDataBase(con);
}
就像你从任何Activity
那样打电话给
NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(yourActivity.This);
就像你从任何Fargment
那样打电话给
NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(getActivity());