hello i am using AsyncHttpClient
to send request to restful
api
the problem is i want to have the result in onSuccess
and pass it from the class who have this method to my activity
public int send(JSONObject parameters,String email,String password){
int i =0;
try {
StringEntity entity = new StringEntity(parameters.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.setBasicAuth(email,password);
client.post(context, "http://10.0.2.2:8080/webapi/add", entity, "application/json",
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
JSONObject json = new JSONObject(
new String(responseBody));
i=statusCode;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return i;
}
of course i always get i=0
; because it's Async
method
i tried to make the method send void
and make a callback inside onSuccess but that produce a lot of problems with the activity (that's another question i will ask later)
so do you have a way to get the value of i as statusCode?
thank you.
I tried to make the method send void and make a callback inside onSuccess
The method being void is good.
Making a callback inside onSuccess can look like this
Add a callback interface
public interface Callback<T> {
void onResponse(T response);
}
Use it as a parameter and make the method void
public void send(
JSONObject parameters,
String email,
String password,
final Callback<Integer> callback) // Add this
Then, inside the onSuccess
method, when you get the result do
if (callback != null) {
callback.onResponse(statusCode);
}
Outside that method, where you call send
, create anonymous callback class
webServer.send(json, "email", "password", new Callback<Integer>() {
public void onResponse(Integer response) {
// do something
}
});