Reputation: 3488
I have an AsyncHttpClient that makes a get request to an url. I will take the response of the method onSuccess(). I paste my code to a better explain..
CategoryActivity.java call method getXML of class "XMLParser". In this method it is the AsyncHttpClient.
XMLParser parser = new XMLParser(URL);
xml = parser.getXML(URL);
XMLParser.java has .getXML(url) and return a String. I create a variable xmlResponse to put response value but it doesn't.
public String getXML(String url) {
// get connection..
String xmlResponse = "";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
xmlResponse = response;
}
@Override
public void onFailure(Throwable e) {
ma.showUserAlertQuestion();
}
});
return xmlResponse;
}
How can I get back this value? Thank you in advance & sorry for my bad english.
Upvotes: 1
Views: 2221
Reputation: 51
This is actually a race condition. The reason why you cannot get the value of xmlResponse
is because your HTTP request is an asynchronous method, the result returned before it gets back the response from the server.
This answer basically explains everything, to get the response value of onSuccess()
, you need to use an interface:
public Interface XMLCallback {
onSuccess(String response);
}
In your parser class:
public String getXML(String url, XMLCallback callback) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
callback.onSuccess(response);
}
@Override
public void onFailure(Throwable e) {
ma.showUserAlertQuestion();
}
});
}
And in your activity class:
private String XMLResponse = "";
XMLParser parser = new XMLParser(URL);
xml = parser.getXML(URL, new XMLCallback() {
@Override
public void onSuccess(String response) {
XMLResponse = response;
}
});
Upvotes: 2
Reputation: 844
I've got the same problem of you in other context. You can see it here: https://stackoverflow.com/questions/21578458/return-asynch-data-to-method-android-java I am also searching for a solution, but didn't find it at this moment.
The reason why you get no results in your return value, is simple. When you do: client.get() the message is send to the server. Than your code goes inmediatly to return xmlResponse. The onSucces method will be called after the return, this is because the software reaches faster the return statement than the message from the Async call is returned by the server.
In the topic I showed you above is a solution for it. But that solution didn't fit for the way I planned my application. Maybe it will fit at your application.
Upvotes: 0