问题描述
我想做的是执行onSuccess
方法时,queryLogin
返回true
,而如果执行onFailuer
方法,则queryLogin
返回false
;但是,正如您所知,在Java中,我无法从内部类修改外部类的值.所以我只是想知道如何解决这个问题并实现我的目标. public static boolean queryLogin(String username, String passowrd){
boolean isSuccess = false;
params.put("username", username);
params.put("password", passowrd);
VStarRestClient.post(LOGIN_URL, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
isSuccess = true;//cannot
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
String responseContent = new String(responseBody);
isSuccess = false;//cannot
}
});
return isSuccess;
}
您正在尝试在此处混合使用同步和异步行为,这是行不通的.
post()
方法仅触发HTTP发布,并且您的登录方法的执行将继续进行到最后,而无需等待该发布的结果.这就是AsyncHttpResponseHandler
的用途.当对post()
的答复到达时会调用它.
网络活动(以及所有其他可能需要很长时间的任务)总是不同步,不会冻结应用程序的用户界面.
What I want to do is when onSuccess
method executed, the queryLogin
return true
,while if onFailuer
method executed , the queryLogin
return false
;But as you know, in java, I cannot modify an outer class value from the inner class. So I just wonder how can I solve the problem and achieve my aim.
public static boolean queryLogin(String username, String passowrd){
boolean isSuccess = false;
params.put("username", username);
params.put("password", passowrd);
VStarRestClient.post(LOGIN_URL, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
isSuccess = true;//cannot
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
String responseContent = new String(responseBody);
isSuccess = false;//cannot
}
});
return isSuccess;
}
You're trying to mix synchronous and asynchronous behaviour here, which cannot work.
The post()
method just triggers a HTTP post and execution of your login method continues to its end without waiting for the result of that post. That's what the AsyncHttpResponseHandler
is here for. It is called when the reply to the post()
arrives.
Network activities (and all other tasks, which might take a long time) are always asynchonously to not freeze the UI of your app.
这篇关于如何将值从内部类返回到外部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!