Reputation: 209
In my main activity, i am opening a new activity like this:
someActivityResultLauncher.launch(myIntent);
In my secondary activity i am invoking a REST api with like this:
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), someRequest.toString());
Request request = new Request.Builder().url(myURL).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
System.out.println(e);
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
System.out.println(response.body().string());
}
});
After that i close the secondary activity returning an object with data i retrieved from the REST api to the main activity.
The problem is that the HTTP call executes on the seperate thread and the main thread is executed before the HTTP call, which means the secondary activity returns the object before it is filled with data.
I tried execute() in order to wait for the HTTP response before returning to the main activity, but this generates an android.os.NetworkOnMainThreadException.
How can i force it to wait for a response before returning to the main activity?
Upvotes: 0
Views: 1035
Reputation: 644
You can use java.util.concurrent.CountDownLatch
:
CountDownLatch latch = new CountDownLatch(1);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), someRequest.toString());
Request request = new Request.Builder().url(myURL).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
System.out.println(e);
//Add line here
latch.countDown();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
System.out.println(response.body().string());
//Add line here
latch.countDown();
}
});
try {
//Await method will stop main thread until calling Latch.countDown();
latch.await(10, //Write here timeout you want
TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Do your stuff with UI here
Upvotes: 1