0
votes

I'm doing a simple 'get' using ASyncHttpClient and its working and giving me the correct json response in the onSuccess() function, but when I try to save the string response to a variable and return that variable in the function, it always returns an empty string.

Code:

public class HttpRequests 
{   
    public String jsonString = "";

    public String add_guest(String name, String id, String hardware_id) 
    { 
        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://www.mysite.com/api.php?name="+name+"&id="+id+"&hardware_id="+hardware_id;

        client.get(url, new JsonHttpResponseHandler() 
        {
            @Override
            public void onSuccess(JSONObject response)
            {
                jsonString = response.toString();
            //this successfully ouputs the json response in LogCat
                Log.d("response:",jsonString);
            }

            @Override
            public void onFailure(Throwable e) 
            {
                Log.d("http error:",e.toString());
            }
        });
        //this returns ""
        return jsonString;
    }
}

Its as if the jsonString inside the onSuccess isn't in the same scope as the jsonString I'm returning. The reason behind this is I have many api calls and want to keep them all in the same class, then call them from other various classes when I need them and just parse the json from there. I tried returning the json object too instead of the string but same deal as this.. it just comes out blank from the other class. (its not setting it properly in onSuccess)

Any ideas..?

EDIT:

Sorry I should have clarified. I AM calling add_guest from my other class. This is from my other class:

String response = "";
HttpRequests myRequest = new HttpRequests();
response = myRequest.add_guest("bob","1","123");

Now by calling add_guest this should in turn call the JsonHttpResponseHandler which 'should' set jsonString to the response and return it.. unless I'm missing something..

1
Does client.get() wait for the response to come in before executing anything after in the add_guest() method or is it completely independent? If it's completely independent, jsonString is returned immediately and 99% of the time will be "". By the way returning "" is not the same as null.A--C
Oh sorry I rewrote some of it in the editor and was originally setting it to null. But anyway - I think it may be independent.. assuming it is, is there a way around this..? Thanks AC :)Jonny07
How are you using the value?A--C
Well the result of each api call will be used differently.. but the majority will be used to retrieve text/images based on that specific users account (once they have logged in) so I need to have full access to the json string/object in code to manipulate the values.. Which is why I was calling it from my main class where I need to work with the response etc. to elaborate - the UI is never being changed on the fly.. these are 1 time requests that only happen once on page load. or when a user clicks a button.Jonny07

1 Answers

3
votes

Let's take a close look at your code:

public class HttpRequests 
{   
    public String jsonString = "";

This declares a member variable named jsonString and initializes it to an empty String.

    public String add_guest(String name, String id, String hardware_id) 
    { 
        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://www.mysite.com/api.php?name="+name+"&id="+id+"&hardware_id="+hardware_id;

        client.get(url, new JsonHttpResponseHandler() 

This creates a JsonHttpResponseHandler object which will be called when the response is available. Note that none of the code in this handler is executed yet. The object is only created.

        {
            @Override
            public void onSuccess(JSONObject response)
            {
                jsonString = response.toString();
            //this successfully ouputs the json response in LogCat
                Log.d("response:",jsonString);
            }

            @Override
            public void onFailure(Throwable e) 
            {
                Log.d("http error:",e.toString());
            }
        });
        //this returns ""
        return jsonString;

As your comment states, this returns "" because none of the handler code has executed. You need to find a way to give the caller the String after the handler has finished.

    }
}

Further Suggestions:

After seeing the code which calls add_guest(), one possible solution that comes to mind is to change add_guest() to return void and add another method to HttpRequests called getResponse(). This method can wait for the response and then return jsonString. In order to do this, you will probably need to declare AsyncHttpClient client as a member variable, rather than local to add_guest(). I am unfamiliar with the AsyncHttpClient class, but I suspect that it has a method that will block until a response has occured.

Another possible solution is to add a HttpRequests(JsonHttpResponseHandler) constructor. Then the class which calls add_guest() can implement JsonHttpResponseHandler (assuming that it is an interface, not an abstract class) and get the response directly.