问题
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?
Problem Solved
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 class
public class FetchData extends AsyncTask<String, String, String> { .... DatabaseHelper db = new DatabaseHelper(); //need context here!!! .... }
Thanks to Kasra, I create a fourh class and use it in MainActivity before calling AsyncTask
ContextStatic class
public class ContextStatic { private static Context mContext; public static Context getmContext() { return mContext; } public static void setmContext(Context mContext) { ContextStatic.mContext = mContext; } }
Updated MainActivity class
public class MainActivity extends Activity {
...
ContextStatic.setmContext(this);
FetchData fetchData = new FetchData();
fetchData.execute();
...
}
回答1:
Try this:
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
}
}
You can call this AsyncTask by the following line - assuming you are in an activity:
new FetchData().execute(this);
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;
}
}
and in your main code, before you call AsyncTask, call this:
myStatic.setContext(this);
in your doInBackground method of your AsyncTask, add this:
Context myContext = myStatic.getContext();
来源:https://stackoverflow.com/questions/28267764/how-to-use-databasehelper-class-in-an-asynctask-class-working-on-a-different-cla