简体   繁体   中英

JsonObjectRequest GET Request retrieves value after method returns value

I am trying to retrieve a JsonObject via GET request. When I set Breakpoints in my code I see that the count() method returns nothing. After that the onResponse method from the inner class gets called and the desired value gets retrieved.

I am calling the count() method inside the save() method. In order to create a JSONObject. The code creates the JSONObject before it retrieves the correct customer count.

I am using a custom requesQueue called AppController to queue the network request. I hope someone understands this strange behaviour.

@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;

The AppController network queue

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);
        }
    }

What's Happening?

This is happening due to incorrect thread usage. count() function performs the network request in the background thread, so it won't return the count immediately when we call it from save() function.

Solution

Wait for the response from count API and then perform a save operation. Replace the above implementation with the following

@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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM