在碎片中传递Asynctask的价值

时间:2013-05-06 07:27:26

标签: android-asynctask fragment

我一直在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);
}

1 个答案:

答案 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();
  }
}

希望对您有帮助。