0

I am using Volley to make Http requests to my Web Api. However I am having trouble getting the values from my api calls due to the asynchronous nature of Volley. I have read that using a callback function could help with this issue, however I do not know how to implement such a solution.

How would I go about implementing a callback function in the following scenario?

public class Main
{
   String name;

   WebServiceConnections wsc = new WebServiceConnections();
   name = wsc.getNameFromWeb();

   System.out.println("Name: " + name);
}  



public class WebServiceConnections
{
    public String getNameFromWeb()
    {
        String url = "http://nameservice.net/GetName";

        JsonArrayRequest req = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    try {
                        return response.getString("Name");
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });
    }
}

The problem with this code is that the variable "name" in Main will be null when it is called by the print statement as the asynchronous method in the WebServiceConnections class will not be finished by time the print statement is called.

Is a callback a good way to solve this problem?

semiColon
  • 205
  • 6
  • 24
  • Pls read my answer at http://stackoverflow.com/questions/32672942/android-volley-library-do-we-always-have-to-repeat-response-listener-and-respon/32674056#32674056 – BNK Mar 11 '16 at 01:13
  • 1
    @BNK Thank you your answer is very helpful! – semiColon Mar 11 '16 at 10:02

1 Answers1

0

Your code doesn't compile - you can't return a value in a method with void return type. Your onResponse method is the callback. Perform the print within the method itself.

Shlomi Uziel
  • 868
  • 7
  • 15
  • I just wrote that segment of code quickly there, it is only meant for reference so that the solution can be explained, not for actually compiling. – semiColon Mar 10 '16 at 20:44
  • I understand that I could perform actions in the volley method.. but if I wanted to use it in the way the example shows would this be possible another way? – semiColon Mar 10 '16 at 20:47
  • Create a class extending Response.Listener instead of an anonymous function. That's the way to go, no need to seek other solutions since that's your callback. – Shlomi Uziel Mar 10 '16 at 20:50