【问题标题】:How to fetch data out of AsyncTask class in android?如何从android中的AsyncTask类中获取数据?
【发布时间】:2017-01-12 21:21:28
【问题描述】:

我想知道如何访问数据并将其绑定到 AsyncTask 类主体之外的组件?

我有这样的课:

class DownloadData extends AsyncTask<String, Void, String> {....}

它有一个方法:

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

        return ....;//return some data
    }

不明白 doInBackground 返回数据到哪里?

因为当我想使用我的课程时,我会像这样使用它:

      DownloadData dd = new DownloadData();
            dd.execute(...);

我可以这样使用它吗?因为我想从我的主类中获取返回的数据以将其绑定到某些组件

      DownloadData dd = new DownloadData();
        string temp=dd.doInBackground(...);

【问题讨论】:

  • 查看答案并确认是否有帮助

标签: java android android-studio android-asynctask


【解决方案1】:

doInBackground() 之后,您的return 将被转发到onPostExecute()

要在您的活动中使用它,请参考此链接:How to use Async result in UIThread

【讨论】:

  • 如果有帮助,请对此答案投票。编码快乐!
【解决方案2】:

抓不住

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

        return ....;//return some data
    }

主界面的结果。

你必须使用回调。例如,您可以使用接口获取结果。

例如创建一个接口:

public interface IProgress {
    public void onResult(int result);
}

创建类:

     private class DownloadData extends AsyncTask<String, Void, String> {
    private IProgress cb;
    DownloadData(IProgress progress)  {
    this.cb = cb;
    }
@Override
protected String doInBackground(String... params) {


for (int i = 0; i < 10; i ++) {
if (cb!=nil)
cb.onResult(i);//calls 10 times
}
....
    }
...
    }

代码中的某处:

DownloadData dd = new DownloadData( new IProgress() {
public void onResult(int result) {
/// this is your callback

//to update mainUI thread use this:
final res = result;
runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //update UI here
textview.setText("" + res);
                }
            });

}
});
            dd.execute(...);

而且,像往常一样,您可以在 doInBackground 之后通过 onPostExecute() 更新 UI

【讨论】:

    【解决方案3】:

    如果您只想从 AsyncTask 类返回一个结果,以便您可以根据结果更新活动中的 UI,您可以执行以下操作: 在你的 AsyncTask 类中声明一个这样的接口:

    private AsyncResponse asyncResponse = null;
    
    public DownloadData(AsyncResponse as) {
        this.asyncResponse = as;
     }
    
    public interface AsyncResponse {
        void onAsyncResponse(String result); // might be any argument length of any type
    }
    

    onPostExecute()

    asyncResponse.onAsyncResponse(result); // result calculated from doInBackground()
    

    在活动类中:

    DownloadData dd = new DownloadData(new AsyncResponse() {...}); // implement onAsyncResponse here
    dd.execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      相关资源
      最近更新 更多