Reputation: 1644
I'm using Android loopj library to have asynchronous HTTP client. I need to set the responseBody
to the image object's property like following but because of asynchronous, the return statement will be run instead and the image object is always null.
public Image uploadImage(boolean async) {
Image image = new Image();
HttpClient.post(getFinalUrl(async), makeRequestParams(), new AsyncHttpResponseHandler
() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
UploadResponse[] uploadResponses = GsonParser.getArrayFromGson(responseBody,
UploadResponse[].class);
UploadResponse response = uploadResponses[0];
String st = response.getContent();
image.setImageAddress(st);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("injaro", error.getMessage());
}
});
}
Upvotes: 0
Views: 47
Reputation: 2867
Async methods don't work this way. You should pass them a callback object which will be called once the response is available.
So if you define a Callback interface like this:
public interface ImageCallback {
void onImageReceived(Image image);
}
Then you could create 2 methods (one synchronous and one asynchronous) like this:
public Image uploadImage() {
...
}
public void uploadImageAsync(ImageCallback callback) {
...
}
At this point you'll just have to call the method you need - i.e. on button click listeners would call the async one (since you don't want to block the UI thread), but your background services could safely call the synchronous one.
Upvotes: 1