I'd like to get access from my database which is the DBAdapter.class (not an activity) into another non-activity class that randoms data RandomData.class
my sample code was like:
DBAdapter getAvailRandom=new DBAdapter(getApplicationContext());
getAvailRandom.open();
...
....
...
getAvailRandom.close();
getApplicationContext()
is always undefined
I tried getActivity.getApplicationContext()
and Activity.this
, but still not working
You need to create One Argument Constructor
and pass Context
like
private Context mContext;
public DBAdapter(Context con){
mContext = con;
}
in your DBAdapter
class
DBAdapter getAvailRandom=new DBAdapter(getApplicationContext());
Pass Context to non-Activity class in there constructor and use that reference where you want. eg
public DBAdapter(Context mCtx){
this.mCtx = mCtx;
}
And for RandomData
public RandomData(Context mCtx){
this.mCtx = mCtx;
}
You should pass the context to the constructor or method you are calling.
private Context mContext;
public RandomData(Context context) {
mContext = context;
}
Edit:
Just for fun, you can actually get the application context in a static way. This is not recommended:
public static Context getContext() {
Context context = null;
try {
Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
Method method = activityThreadClass.getMethod("currentApplication");
context = (Application) method.invoke(null, (Object[]) null);
} catch (Exception ignored) {
}
return context;
}
You can not access getApplicationContext()
in normal java class so you will need to use RandomData
class constructor to get Context from Activity as:
Context context;
RandomData(Context context){
this.context=context;
}
Now pass context in DBAdapter
constructor :
DBAdapter getAvailRandom=new DBAdapter(context);
Another possibility to avoid storing a reference to the whole context of your application and rendering the non-activity class dependent on the lifespan of your context is to provide (static-)methods which take a context as an parameter.
In this manner:
public static void doDbStuff(Context context, ...) { .. }
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.