【问题标题】:Android generic AsynctaskAndroid 通用 Asynctask
【发布时间】:2015-06-16 15:31:24
【问题描述】:

我目前有多个活动需要为 http post 执行 asynctask,我希望将 asynctask 作为另一个类文件,以便不同的活动可以调用 asynctask 来执行 http post 请求和 onPostExecute,调用方法 httpResult (结果)在调用异步任务的活动中。我试图传递活动,但我无法在 onPostExecute 中调用该方法。我该怎么做?

public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_MyActivity);

    //logic here...
    AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
    JSONObject data = new JSONObject();
    data.put("key", "value");
    try {
            asyncHttpPost.execute(data);
        }
        catch (Exception ex){
        ex.printStackTrace();
        }
    }
    public static void httpResult(String result) {
        //this method has to get called by asynctask to make changes to the UI
     }

}

AsyncHttpPost.java

public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private Activity activity;


public AsyncHttpPost(String data, Activity activity, ProgressDialog dialog) {
    mData = data;
    this.activity = activity;
    this.dialog = dialog;
}

protected void onPreExecute()
{

    dialog.show();
}

    @Override
    protected String doInBackground(JSONObject... params) {

       //logic to do http request
           return "someStringResult";

    }

    protected void onPostExecute(String result) {
        dialog.dismiss();
        activity.httpResult(result); //This line gives me error : The method httpResult(String) is undefined for the type Activity


    }
}

【问题讨论】:

  • 你能发布你的代码并解释问题..
  • 您应该发布您的代码,以便更轻松地解决您的问题。
  • 用示例代码编辑了我的问题
  • 从函数httpResult中移除静态标识符,所以将public static void httpResult(String result)改为public void httpResult(String result)
  • Sherif:我从 httpResult 函数中删除静态后出现同样的错误

标签: android android-asynctask


【解决方案1】:

在单独的文件中创建一个名为 HttpResponseImpl 的接口,并添加所需的方法httpResult

interface HttpResponseImpl{
    public void httpResult(String result);
}

现在由你实现这个接口Activity

public class MyActivity extends Activity implements HttpResponseImpl{

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_MyActivity);

    //logic here...
    AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
    JSONObject data = new JSONObject();
    data.put("key", "value");
    try {
            asyncHttpPost.execute(data);
        }
        catch (Exception ex){
        ex.printStackTrace();
        }
    }

    public void httpResult(String result){
        //this method has to get called by asynctask to make changes to the UI
    }
}

你的 AsyncHttpPost 类将是。

public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private HttpResponseImpl httpResponseImpl;


public AsyncHttpPost(String data, HttpResponseImpl httpResponseImpl, ProgressDialog dialog) {
    mData = data;
    this.httpResponseImpl = httpResponseImpl;
    this.dialog = dialog;
}

protected void onPreExecute()
{

    dialog.show();
}

    @Override
    protected String doInBackground(JSONObject... params) {

       //logic to do http request
           return "someStringResult";

    }

    protected void onPostExecute(String result) {
        dialog.dismiss();
        httpResponseImpl.httpResult(result); 


    }
}

实现这个HttpResponseImpl 接口与所有你想要从其执行HttpRequest 的Activity 类。

【讨论】:

  • 这适用于单个活动,但我有一些活动也会使用此异步任务,我无法列出所有活动,对吗?
  • 亲爱的,你的方法是错误的,你传递了一个 Activity 类,它自己没有方法 httpResult(String result)
  • 根据您的要求,您应该尝试回调机制或观察者侦听器模式。
  • Anieeh:如果您能提供代码示例供我尝试,不胜感激?
【解决方案2】:

通用 AsyncTask 示例

这样称呼

new RetrieveFeedTask(new OnTaskFinished()
        {
            @Override
            public void onFeedRetrieved(String feeds)
            {
                //do whatever you want to do with the feeds
            }
        }).execute("http://enterurlhere.com");

RetrieveFeedTask.class

class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
    String HTML_response= "";

    OnTaskFinished onOurTaskFinished;


    public RetrieveFeedTask(OnTaskFinished onTaskFinished)
    {
        onOurTaskFinished = onTaskFinished;
    }
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... urls)
    {
        try
        {
            URL url = new URL(urls[0]); // enter your url here which to download

            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String inputLine;

            while ((inputLine = br.readLine()) != null)
            {
                // System.out.println(inputLine);
                HTML_response += inputLine;
            }
            br.close();

            System.out.println("Done");

        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return HTML_response;
    }

    @Override
    protected void onPostExecute(String feed)
    {
        onOurTaskFinished.onFeedRetrieved(feed);
    }
}

OnTaskFinished.java

public interface OnTaskFinished
{
    public void onFeedRetrieved(String feeds);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多