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..
client.get()
wait for the response to come in before executing anything after in theadd_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 asnull
. – A--C