如何将值从内部类返回到外部类? [英] How to return the value from inner class to outer class?

查看:169
本文介绍了如何将值从内部类返回到外部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是执行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.

这篇关于如何将值从内部类返回到外部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆