4
我有一個「GameActivity」,爲了填充佈局,我必須對遠程API進行多次調用,並想知道使用AsyncHttpClient包http://loopj.com/android-async-http/完成此操作的最佳方法。多個AsyncHttpClient獲取請求來填充一個活動
我目前的設置爲一個單一的API調用:
public class MainActivity extends Activity implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener{
ListView mainListView;
JSONMainAdapter mJSONAdapter;
SwipeRefreshLayout swipeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.main_swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
mainListView = (ListView) findViewById(R.id.main_listview);
mainListView.setOnItemClickListener(this);
mJSONAdapter = new JSONMainAdapter(this, getLayoutInflater());
mainListView.setAdapter(mJSONAdapter);
getGameDetails();
}
所以我getGame細節將是第一個電話,後來我就需要做更多的4-6。
我getGameDetails:
private void getGames() {
swipeLayout.setRefreshing(true);
MyRestClient.get("games", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
swipeLayout.setRefreshing(false);
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
mJSONAdapter.updateData(jsonObject.optJSONArray("games"));
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
swipeLayout.setRefreshing(false);
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
Log.e("ERROR", statusCode + " " + throwable.getMessage());
}
});
}
所以我的想法是添加一個函數在每次調用我需要的,只是叫他們一個接一個地在我之後的onCreate像這樣:
getGameDetails();
getGameCallA();
getGameCallB();
getGameCallC();
其他方法將是調用AsyncHttpClient的onSuccess方法中的下一個函數,但這看起來不正確。
問:是否有一個「批量請求」與我應該在這裏使用的AsyncHttpClient?
任何輸入讚賞,謝謝。
我想說明的方式來調用onSuccess方法中的下一個函數看起來更加正確。因爲在我的情況下,你會順序執行http請求,但是你不能保證下一個http請求會比先前的onSucess塊中的代碼慢。另外如果你的第一個請求返回onError呢?是否要繼續執行下一個請求? –
我想到的越多,我認爲你是對的 - 我只需使用onSuccess來調用其他api調用。首先檢查它看起來像是非線性的非OO方法。所以假設沒有隱藏在AsyncHttpClient中的「批量」請求功能,這就足夠了。 – canigetabreak