android - 需要按顺序发送多个 Volley 请求

标签 android android-volley

我需要使用 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/

相关文章:

android - ViewModel 观察者方法返回 null

java - 对 CONTENT_FILTER_URI 结果进行排序

android - 在 Android 上使用 Volley 获取 SSLHandshakeException

android - Android 中的 PATCH 动词(OkHttp、Volley、Retrofit...)

Android EDL 模式指令

Android:防止用户在登录后返回登录页面

android - Android Volley 的 onResponse 方法未执行

尝试使用 Volley 更新数据库时出现 Php 错误

java - Android 在另一个弧内绘制一个弧

android - Volley - DiskBasedCache OutOfMemory 异常 - 数组大小太大