问题似乎是你想要你并且你没有得到它。 您的函数getNumber()执行TopDown,但您正在进行的请求是Asychronous, 在不同的线程上运行 。 因此,在您回国时uId ,存在没有价值uId 。 走出了回调的call.enqueue了,我的意思是onResponse()和onFailure()有没有办法,你可以得到uId在onFailure ,这是显而易见的,但它是不是太明显了,你会得到uId在`onResponse( )”。 从javadoc for Retrofit:
onResponse void onResponse(Call call, Response response)
为收到的HTTP响应调用。 注意:HTTP响应可能仍指示应用程序级别的故障,例如404或500.调用Response.isSuccessful()以确定响应是否表示成功。
因此在onResponse您仍然需要放置一些代码以确保您获得uId然后只返回它。 并且不要直接返回uId ,设置为某个字符串(全局)并在确保它可用后访问它。
所以改变你的代码就像::
public void getNumber() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call call = apiInterface.getTopLead();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccesful(){
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);
//output: Return uid
Log.i("Return"," uid" + uId);
} else {
onCallCallback.showToast("Could not load phone number");
}
} else{
Log.e("in ", " response is not successful" )
}
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
这仍然在不同的线程上运行,因此uId将在一段时间后设置。 设置后,您可以使用该值。 如果要在主线程上运行并使用call.execute().body();获取uId也可以使用Synchronous请求call.execute().body(); 返回TopLead对象,然后你可以得到uId从疗法e。使用topLead.getUId.toString()
我希望它有所帮助,请在评论中询问是否需要澄清。