I am currently creating an Android app and encounter an issue and I haven't solved yet.
I use the Retrofit library to send requests to a server, according to the Retrofit library it is done in a background thread.
I call this Retrofit request in the main thread and I want to wait for this background thread to finish in order to work on its output.
I found a similar question on the forum but I don't know how to implement : Android: how to wait AsyncTask to finish in MainThread?
I call the request with Retrofit, when the request is finished, the success method of the Callback object starts, but main thread is still running and it reaches the last line before the background task has finished.
How can I force my main thread to wait for the background task to finish ?
My code :
// ... (main thread)
// CALL TO THE SERVER
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(LoginScreen.ENDPOINT).build();
WebServices getFiles = restAdapter.create(WebServices.class);
Callback<Response> callback = new Callback<Response>()
{
@Override
public void success(Response s, Response response)
{
fileAvailable = new String(((TypedByteArray) s.getBody()).getBytes());
//THIS IS EXECUTED WHEN THE BACKGROUND TASK IS FINISHED
}
@Override
public void failure(RetrofitError retrofitError)
{
Log.e(TAG, retrofitError.toString());
}
};
getFiles.getFiles(id, callback);
// I want here to work with fileAvailable, but the code
// reaches this line before the background task is over.
I tried to create a Handler object as in the previous link and call sendEmptyMessage in the success method but it didn't work.
I would be really grateful if somebody could help me.
Thank you in advance,