I have an api that it workes in Asynchronous mode but not work in Synchronous mode. I have an ApiUtils class :
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://jsonplaceholder.typicode.com/";
public static APIServices getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIServices.class);
}
}
And have RetrofitClient class :
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
My Post ViewModel class is :
public class Post {
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
@SerializedName("userId")
@Expose
private Integer userId;
@SerializedName("id")
@Expose
private Integer id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Post{" +
"title='" + title + '\'' +
", body='" + body + '\'' +
", userId=" + userId +
", id=" + id +
'}';
}
}
My gradle dependencies is :
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.4'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
And i granted internet permission in android manifest . And i wrote 2 functions for Async calling and Sync calling for that api . But the problem is my Async method workes but my Sync method not workes :
//Not work
private void SyncCall() {
Call<Post> ins= mAPIServices.savePost("test title", "test body", 12);
try {
String s =ins.execute().body().toString();
} catch (IOException e) {
e.printStackTrace();
}
}
//Worked
private void AsyncCall() {
mAPIServices.savePost("test title", "test body", 12)
.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
String s = response.body().toString();
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}