2016-09-05 26 views
0

我想知道如何訪問數據並將其綁定到AsyncTask類主體之外的組件?如何從android中的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(...); 
+0

查看答案並覈准是否有幫助 – Vyacheslav

回答

0

我無法趕上從主UI

@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之後更新UI onPostExecute()

0

如果你只是想從你的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(); 
相關問題