多个AsyncHttpClient获取填充一个活动的请求

时间:2014-05-06 03:08:59

标签: android android-layout asynchttpclient

我有一个" GameActivity"为了填充布局,我必须多次调用远程API,并想知道使用AsyncHttpClient包http://loopj.com/android-async-http/完成此任务的最佳方法。

我目前为单个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吗?

感谢任何意见,谢谢。

1 个答案:

答案 0 :(得分:4)

我无法验证它是否有效,但我想有办法一个接一个地执行你的请求

在您的班级MyRestClient中:

private static AsyncHttpClient client = new AsyncHttpClient();
static {
    client.setThreadPool(Executors.newSingleThreadExecutor());
}

之后你只需致电:

getGameDetails();
getGameCallA();
getGameCallB();
getGameCallC();