我知道这是一个常见问题,但我都做了,但仍未解决。在我的 MainActivity 中,我收到了来自 ServerService.java 的呼叫,如下所示:
String randomNumber = serverService.contactServer();
在 ServerService.java 中, contactServer()将调用包含.enqueue的方法:
public String contactServer() {
return requestServerService();
}
requestServerService()包含以下代码:
public String requestServerService() {
Call<RequestAttributes> call = new RetrofitConfig().getServiceRequester().requestRandomNumber();
call.enqueue(new Callback<RequestAttributes>() {
@Override
public void onResponse(Call<RequestAttributes> call, Response<RequestAttributes> response) {
if (!response.isSuccessful()) {
Log.i("Err", "Err: " + response.code());
} else {
RequestAttributes requestAttributes = response.body();
returnedValue = requestAttributes.getRandomNumber();
Log.d("jsonAnswer", "O numero aleatorio é: " + returnedValue);
}
}
@Override
public void onFailure(Call<RequestAttributes> call, Throwable t) {
Log.e("Fail", "Failed: " + t.getMessage());
}
}); return returnedValue;
错误是 returnedValue 返回空值。我尝试了调试,但即使没有达到onReponse。我知道问题一定是因为.enqueue是异步的,但是如何解决此问题并将请求返回给 mainActivity ?
改造的配置:
public RetrofitConfig() {
this.retrofit = new Retrofit.Builder()
.baseUrl("localhost:3000/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public ServiceRequester getServiceRequester() {
return this.retrofit.create(ServiceRequester.class);
}
POJO :
public class RequestAttributes {
@SerializedName("randomNumber")
private String randomNumber;
public String getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(String randomNumber) {
this.randomNumber = randomNumber;
}
@Override
public String toString() {
return "RequestAttributes{" +
", randomNumber='" + randomNumber + '\'' +
'}';
}
}
和请求:
@GET("api/requestRandomNumber")
Call<RequestAttributes> requestRandomNumber();
JSON答案(如果我通过浏览器请求)
{"randomNumber":"u845gq"}
答案 0 :(得分:0)
您可以将回调从MainActivity
传递到contactServer()
方法
serverService.contactServer(new Callback<RequestAttributes>() {
@Override
public void onResponse(Call<RequestAttributes> call, Response<RequestAttributes> response) {
if (!response.isSuccessful()) {
Log.i("Err", "Err: " + response.code());
} else {
RequestAttributes requestAttributes = response.body();
String returnedValue = requestAttributes.getRandomNumber();
// Do what you want here with returnedValue. You are in the activity thread(MainThread or UIThread) for example someTextView.setText(returnedValue);
Log.d("jsonAnswer", "O numero aleatorio é: " + returnedValue);
}
}
@Override
public void onFailure(Call<RequestAttributes> call, Throwable t) {
Log.e("Fail", "Failed: " + t.getMessage());
}
});
然后将其设为void
方法,并将回调传递给requestServerService()
方法
public void contactServer(Callback<RequestAttributes> callback) {
requestServerService(callback);
}
然后实现如下的requestServerService()
方法:
public void requestServerService(Callback<RequestAttributes> callback) {
Call<RequestAttributes> call = new RetrofitConfig().getServiceRequester().requestRandomNumber();
call.enqueue(callback);
}