我一直在onPostExecute
传递由AsyncTask
Fragment
创建的结果。
我知道如何在Activity
中执行此操作,例如((MyActivity)context).someMethod();
但是我如何在Fragment
?
我做((MyFragment)contextOfAsyncTask).methodInFragment()
但它给了我一个错误“无法从Context转换为MyFragment”。
这是我在AsyncTask中的代码
类AsyncMethod扩展了AsyncTask {
ArrayList<MyObject> myVar= new ArrayList<MyObject>();
String result;
ListView lv;
Context contextOfAsyncTask;
public AsyncMethod(Context xc, ListView xl){
contextOfAsyncTask= xc;
lv = xl;
}
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void...param) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(http://www.myurl.com/something.php);
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
return null; //EVERYTHING IS WORKING FINE HERE, AND I CAN GET THE VALUE
}
@Override
protected void onPostExecute(Void res) {
//it does not work here
((MyFragment)contextOfAsyncTask).methodInFragment(result);
}
答案 0 :(得分:0)
您似乎想从AsyncTask
调用方法
class YourTask extends AsyncTask<Void, Void, Void> {
private SomeFragment fragment;
YourTask(SomeFragment fragment) {
this.fragment = fragment;
}
@Override
protected Void doInBackground(Void... params)
{
//do whatever you want to do
}
@Override
protected void onPostExecute(Void res)
{
fragment.yourmethod();
}
}
希望对您有帮助。