在本課程中,我正在創建一個應用程序「新聞閱讀器」。基本上,我需要從API(首先AsyncTask
調用)獲得新聞的ID,然後使用這些ID,我得到每篇新聞文章(第二次Async調用)的數據,並且在那個數據中有一個URL導致那篇文章。 當我獲得URL時,我將它存儲在數據庫中,稍後會使用它。 在過程中,它與Java的使用AsyncTask
getNews news = new getNews();
String result = news.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
完成,沒有使用onPostExecute()
,我想使用它。
所以,這裏是獲取物品的ID的(第一個異步調用)
public class getNews extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
URL url;
String result = "";
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
}
catch (Exception e){
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
try {
JSONArray jsonArray = new JSONArray(s);
//System.out.println("asasd" + jsonArray);
for(int i = 0; i< 20; i++){
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
的onPostExecute()
內部,通過我得到的數據循環上課的時候,我必須做出一個異步調用每ID我得到了這些數據。
那麼,有沒有辦法做到這一點,而無需創建一個使用AsyncTask
另一個類?
爲什麼你不只是做在'AsyncTask'的'doInBackground()'一切?沒有說你必須解析'onPostExecute()'中的JSON。 –
嗯,那很簡單。謝謝你,有時候解決方案非常簡單,我監督他們。 –
聽起來像RxJava的優秀用例 –