Search code examples
javaandroidjsonreturnandroid-volley

Return data from my StringRequest - Volley lib


In my project i receive data from my server using the "Volley" lib, I made PHP file which returns JSON encoded values and I want to take those values and return them from and not just process them inside the StringRequest,

My code is:

public static void getStatus(final String id, final Marker marker1)
    {
        // Tag used to cancel the request
        String tag_string_req = "req_register";
        temp="";
        StringRequest strReq = new StringRequest(
                Request.Method.POST,
                "http://URL/file.php",
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {



                        try {
                            JSONObject jObj = new JSONObject(response);
                            String status = jObj.getString("string");
                            temp = status;


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to getData url
                Map<String, String> params = new HashMap<String, String>();
                params.put("id", id);
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }

How can i return the string "status" from this method? (If i change the method to String from void I still couldn't return any values from inside the onResponse (idk why...))? please explain to me why and how can I make it work?


Solution

  • The short answer is that you don't return. Nor should you.

    Instead, you pass the result into whatever code block you want to do next. This could be a separate method or could all be done from within the StringRequest onResponse.

    The main point is that you can't assign temp at the top, set it within the StringRequest, then expect a value on the line after addToRequestQueue