我需要使用 volley 发送请求以检索 membershipid,然后将该成员(member) id 传递到第二个 volley 请求以检索该成员的统计信息。
我的第一个请求完美运行时遇到问题,但第二个请求似乎在变量返回传递之前就开始了。任何人都知道如何防止第二个请求在返回值之前启动?
最佳答案
您不能只按顺序编写每个请求并等待在每个成功响应之后执行每个请求...您必须在第一个服务响应中调用第二个请求...即
public void firstServiceCall(String url)
{
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
int membershipid=response.getInt("membershipid");
//suppose the membershipid comes under main json with key "membershipid"
secondServiceCall(membershipid,<url2>);
// on the response of first service ... call to the second service ... and continue so on... if required
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getApplicationContext()).add(jsonObjReq);
}
public void secondServiceCall(int membershipid,String url)
{
// use this var membershipid acc to your need ...
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getApplicationContext()).add(jsonObjReq);
}
also the request call is asynchronous hence... the other process won't wait for service call to finish...hence your second service starts before the first service response
关于android - 需要按顺序发送多个 Volley 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228364/