我需要返回值uId。我在onResponse()函数内的第一个日志语句中获得了正确的值。但是当涉及到 return 语句时,它返回null。
我认为 onResponse() 正在另一个线程上运行。如果是这样,我怎样才能让getNumber()函数等待onResponse()函数完成执行。(如 thread.join())
或者还有其他解决方案吗?
代码 :
String uId;
public String getNumber() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<TopLead> call = apiInterface.getTopLead();
call.enqueue(new Callback<TopLead>() {
@Override
public void onResponse(Call<TopLead> call, Response<TopLead> response) {
String phoneNumber;
TopLead topLead = response.body();
if (topLead != null) {
phoneNumber = topLead.getPhoneNumber().toString();
uId = topLead.getUId().toString();
//dispaly the correct value of uId
Log.i("PHONE NUMBER, UID", phoneNumber +", " + uId);
onCallCallback.showToast("Calling " + phoneNumber);
} else {
onCallCallback.showToast("Could not load phone number");
}
}
@Override
public void onFailure(Call<TopLead> call, Throwable t) {
t.printStackTrace();
}
});
//output: Return uid null
Log.i("Return"," uid" + uId);
return uId;
相关分类