JsonObjectRequest GET 方法返回值后请求获取值

Posted

技术标签:

【中文标题】JsonObjectRequest GET 方法返回值后请求获取值【英文标题】:JsonObjectRequest GET Request retrieves value after method returns value 【发布时间】:2021-07-23 03:01:20 【问题描述】:

我正在尝试通过 GET 请求检索 JsonObject。当我在代码中设置断点时,我看到 count() 方法没有返回任何内容。之后调用内部类的 onResponse 方法并检索所需的值。

我在 save() 方法中调用 count() 方法。为了创建一个 JSONObject。代码在检索正确的客户数量之前创建 JSONObject。

我正在使用一个名为 AppController 的自定义 requesQueue 来对网络请求进行排队。我希望有人能理解这种奇怪的行为。

@Override
    public void save(Customer customer) throws JSONException 

        int zw = count();
        JSONObject obj = new JSONObject();
        obj.put("customernumber", count + 1);
        obj.put("name", customer.getName());
        obj.put("lastname", customer.getLastname());
        obj.put("phonenumber", customer.getPhonenumber());
        obj.put("addressid", customer.getAdressID());
        obj.put("password", customer.getPassword());

        String urlJsonObj = URL;
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                urlJsonObj, obj,
                new Response.Listener<JSONObject>() 

                    @Override
                    public void onResponse(JSONObject response) 
                        System.out.println(response);
                    
                , new Response.ErrorListener() 

            @Override
            public void onErrorResponse(VolleyError error) 
                VolleyLog.d("Error: " + error.getMessage());

            
        );
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    

@Override
    public int count() 

        String countURL = URL + "/count";


        JsonObjectRequest jsonObjReq = new JsonObjectRequest
                (Request.Method.GET, countURL, null, new Response.Listener<JSONObject>() 

                    @Override
                    public void onResponse(JSONObject response) 


                        try 
                            // Parsing json object response
                            // response will be a json object
                            count = response.getInt("count");
                         catch (JSONException e) 
                            e.printStackTrace();
                        

                    
                , new Response.ErrorListener() 

                    @Override
                    public void onErrorResponse(VolleyError error) 
                        VolleyLog.d( "Error: " + error.getMessage());
                    
                );

        AppController.getInstance().addToRequestQueue(jsonObjReq);

        return count;

AppController 网络队列

public class AppController extends Application 

    public static final String TAG = AppController.class
            .getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() 
        super.onCreate();
        mInstance = this;
    

    public static synchronized AppController getInstance() 
        return mInstance;
    

    public RequestQueue getRequestQueue() 
        if (mRequestQueue == null) 
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        

        return mRequestQueue;
    


    public <T> void addToRequestQueue(Request<T> req, String tag) 
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    

    public <T> void addToRequestQueue(Request<T> req) 
        req.setTag(TAG);
        getRequestQueue().add(req);
    

    public void cancelPendingRequests(Object tag) 
        if (mRequestQueue != null) 
            mRequestQueue.cancelAll(tag);
        
    

【问题讨论】:

【参考方案1】:

发生了什么?

这是由于线程使用不正确造成的。 count()函数在后台线程中执行网络请求,所以当我们从save()函数调用它时它不会立即返回计数。

解决方案

等待计数 API 的响应,然后执行保存操作。将上面的实现替换为以下

@Override
public void save(Customer customer) throws JSONException 
    count();
 

private void performSave(Customer customer, int count) throws JSONException 

    int zw = count; // Finally received the count
    JSONObject obj = new JSONObject();
        obj.put("customernumber", count + 1);
        obj.put("name", customer.getName());
        obj.put("lastname", customer.getLastname());
        obj.put("phonenumber", customer.getPhonenumber());
        obj.put("addressid", customer.getAdressID());
        obj.put("password", customer.getPassword());
    String urlJsonObj = URL;
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            urlJsonObj, obj,
            new Response.Listener<JSONObject>() 

                @Override
                public void onResponse(JSONObject response) 
                    System.out.println(response);
                
            , new Response.ErrorListener() 

        @Override
        public void onErrorResponse(VolleyError error) 
            VolleyLog.d("Error: " + error.getMessage());

        
    );
    AppController.getInstance().addToRequestQueue(jsonObjReq);


@Override
public int count(Customer customer) 

    String countURL = URL + "/count";


    JsonObjectRequest jsonObjReq = new JsonObjectRequest
            (Request.Method.GET, countURL, null, new Response.Listener<JSONObject>() 

                @Override
                public void onResponse(JSONObject response) 


                    try 
                        // Parsing json object response
                        // response will be a json object
                        count = response.getInt("count");
                        performSave(customer, count);
                     catch (JSONException e) 
                        e.printStackTrace();
                    

                
            , new Response.ErrorListener() 

                @Override
                public void onErrorResponse(VolleyError error) 
                    VolleyLog.d( "Error: " + error.getMessage());
                
            );

    AppController.getInstance().addToRequestQueue(jsonObjReq);
    return 0; // Remove this return type as we will not use it anymore

【讨论】:

以上是关于JsonObjectRequest GET 方法返回值后请求获取值的主要内容,如果未能解决你的问题,请参考以下文章

Android Volley 为啥 JsonObjectRequest 不调用 onResponse

jsonObjectRequest 错误消息为空

Volley JsonObjectRequest Post 参数不再起作用

Volley JsonObjectRequest Post 请求忽略参数

Android-Volley网络通信框架(StringRequest &amp; JsonObjectRequest)

带有参数的 Volley jsonObjectRequest 不起作用