Make A Call Synchronously With Loopj Android Asynchronous Http Client
I'm trying to use setUseSynchronousMode on loopj to wait for results of http call before continuing in one case. I tried: AsyncHttpResponseHandler responseHandler = new AsyncHt
Solution 1:
You should have used SyncHttpClient instead of AsyncHttpClient. setUseSynchronousMode doesn't have the desired effect for AsyncHttpClient.
Solution 2:
To have synchronous version of AsyncHttpClient with an ability to cancel it, I do everything on the main thread. Previously I was running it in AsyncTask and as soon as AsyncHttpClient.post() was called, the AsyncTask would finish and I was unable to keep track the AsyncHttpClient instance.
SyncHttpClient didn't allow me to cancel the uploading so I knew I had to use AsyncHttpClient and make appropriate changes.
Following is my class to upload a file which uses AsyncHttpClient and allows cancellation:
publicclassAsyncUploader {
private String mTitle;
private String mPath;
private Callback mCallback;
publicvoidAsyncUploader(String title, String filePath, MyCallback callback) {
mTitle = title;
mPath = filePath;
mCallback = callback;
}
publicvoidstartTransfer() {
mClient = newAsyncHttpClient();
RequestParamsparams=newRequestParams();
Filefile=newFile(mPath);
try {
params.put("title", mTitle);
params.put("video", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mClient.setTimeout(50000);
mClient.post(mContext, mUrl, params, newResponseHandlerInterface() {
@OverridepublicvoidsendResponseMessage(HttpResponse response)throws IOException {
HttpEntityentity= response.getEntity();
if (entity != null) {
InputStreaminstream= entity.getContent();
// TODO convert instream to JSONObject and do whatever you need to
mCallback.uploadComplete();
}
}
@OverridepublicvoidsendProgressMessage(int bytesWritten, int bytesTotal) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}
@OverridepublicvoidsendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
mCallback.failedWithError(error.getMessage());
}
});
}
/**
* Cancel upload by calling this method
*/publicvoidcancel() {
mClient.cancelAllRequests(true);
}
}
This is how you can run it:
AsyncUploaderuploader=newAsyncUploader(myTitle, myFilePath, myCallback);
uploader.startTransfer();
/* Transfer started *//* Upon completion, myCallback.uploadComplete() will be called */To cancel the upload, just call cancel() like:
uploader.cancel();
Post a Comment for "Make A Call Synchronously With Loopj Android Asynchronous Http Client"