0

我一直在努力传递由in创建onPostExecute的结果。我知道如何做到这一点,比如 但我怎么能做到这一点?AsyncTaskFragmentActivity((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);
}
4

1 回答 1

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

我希望它有帮助..

于 2019-12-30T10:25:42.820 回答