问题描述
大家好,我被困在了一个点上,问题是我有下面显示的三个类,我想在 AsyncTask 类中实例化我的 DatabaseHelper 类.能否请您帮忙,我如何在 AsyncTask 类中获取上下文?
Hi everybody I was stuck at a point, the problem is that I have three classes shown below and I want to instantiate my DatabaseHelper class in AsyncTask class. Could you please help, how can I get context in AsyncTask class?
问题已解决
MainActivity 类
MainActivity class
public class MainActivity extends Activity {
...
FetchData fetchData = new FetchData();
fetchData.execute();
...
}
数据库助手
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
....
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
....
}
FetchData 类
FetchData class
public class FetchData extends AsyncTask<String, String, String> {
....
DatabaseHelper db = new DatabaseHelper(); //need context here!!!
....
}
#
感谢 Kasra,我创建了一个 Fourh 类并在调用 AsyncTask 之前在 MainActivity 中使用它
#
Thanks to Kasra, I create a fourh class and use it in MainActivity before calling AsyncTask
ContextStatic 类
ContextStatic class
public class ContextStatic {
private static Context mContext;
public static Context getmContext() {
return mContext;
}
public static void setmContext(Context mContext) {
ContextStatic.mContext = mContext;
}
}
更新了 MainActivity 类
public class MainActivity extends Activity {
...
ContextStatic.setmContext(this);
FetchData fetchData = new FetchData();
fetchData.execute();
...
}
推荐答案
试试这个:
private class FetchData extends AsyncTask<Context, Void, Void> {
protected Long doInBackground(Context... c) {
Context myContext = c[0];
// Do your things here....
}
protected void onPostExecute() {
// Insert your post execute code here
}
}
您可以通过以下行调用此 AsyncTask - 假设您在活动中:
You can call this AsyncTask by the following line - assuming you are in an activity:
new FetchData().execute(this);
<小时>
如果你不能改变你的 AsyncTask 减速,那么你可以尝试使用一个静态变量——尽管它不如 AsyncTask 减速那么有效和漂亮.试试这个:
if You cannot change your AsyncTask deceleration, then you can try using a static variable - although it is not as efficient and pretty as AsyncTask deceleration. Try this:
Class myStatic{
private static Context mContext;
static public void setContext(Context c);
mContext = c;
}
static public Context getContext(){
return mContext;
}
}
在你的主代码中,在你调用 AsyncTask 之前,调用这个:
and in your main code, before you call AsyncTask, call this:
myStatic.setContext(this);
在 AsyncTask 的 doInBackground 方法中,添加:
in your doInBackground method of your AsyncTask, add this:
Context myContext = myStatic.getContext();
这篇关于如何在处理不同类的异步任务类中使用 databasehelper 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!