I've searched a lot about this but can't find any solution. I have been using Volley for a long time to handle my network communication. Recently I decided to use a SyncAdapter
to sync my data to the server. Inside the onPerformSync()
method, I thought I'll use Volley to send the data to the server as its very easy with Volley to make GET, POST requests.
Problem - SyncAdapter
and Volley both use their own seperate threads. So when I initiate a Volley request from inside the onPerformSync()
method, the SyncAdapter
does not wait for the Volley request to complete and finishes the sync before the onResponse()
or onErrorResponse()
callback of Volley is received. I need to make further network calls inside the SyncAdapter
after first call returns successfully.
Example Code -
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
JsonObjectRequest jReq = new JsonObjectRequest(Method.POST, url, data,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "response = " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "error = " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jReq);
//onPerformSync() exits before request finished
}
Question - So how do I make the SyncAdapter
to wait until the network response is received by Volley?
Make a synchronous volley request.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);
and then use:
try {
JSONObject response = future.get(); // this will block (forever)
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
}
Code from: Can I do a synchronous request with volley?