如果saveChanges函数给我真正的价值,我想运行changesHasBeenSaved。 改造完成后,如何获取布尔值或字符串或整数(任意值)? 有可能吗?
我需要一个类似的功能:
public boolean saveChanges()
{
Boolean output = false;
RequestAPI requestAPI = Requests.getRetrofit();
Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();
jsonObjectCall.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
if(response.body() != null) {
output = true;
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
}
});
return output;
}
答案 0 :(得分:2)
您应将方法返回类型boolean
更改为void
,以进行异步改造。
您应该传递侦听器/回调以获取回调状态。
首先创建如下所示的回调接口
public interface ApiCallback {
void onResponse(boolean success);
}
saveChanges如下所示
public void saveChanges(final ApiCallback callback)
{
RequestAPI requestAPI = Requests.getRetrofit();
Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();
jsonObjectCall.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
callback.onResponse(response.body() != null);
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
callback.onResponse(false);
}
});
}
然后您需要调用如下的saveChanges方法
saveChanges(new ApiCallback () {
public void onResponse(boolean success){
if(success){
// do something
} else{
// do something
}
}
});
答案 1 :(得分:0)
jsonObjectCall.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
//when the response is successful
if(response.isSuccessful()) {
output = true;
// display response as string
Log.i(TAG, "post submitted to API." + response.body().toString());
//Object user1 = response.body(); maps response to the modal class
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
}
})
您回叫到上面的更改,包括注释以明确使用。
希望这会有所帮助。