简体   繁体   English

布尔方法不能返回任何内容

[英]Boolean method can not return anything

I am working on an Android app, and now I am writing some methods for the login system. 我正在开发一个Android应用程序,现在我正在为登录系统编写一些方法。 I am trying to create a boolean method that returns true or false according to the response of the server. 我试图创建一个boolean方法,根据服务器的响应返回true或false。 This is my code: 这是我的代码:

public static boolean login(final String name, final String password) {

    final boolean result;
    Thread nt = new Thread() {
        @Override
        public void run() {


            URL url;
            HashMap<String, String> postDataParams = new HashMap<String, String>();

            postDataParams.put("name", name);
            postDataParams.put("password", password);

            try {

                url = new URL("");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);


                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));

                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    return true;
                } else {
                    return false;
                }

            } catch (Exception e) {
                return false;
                e.printStackTrace();
            }
        }

    };
    nt.start();
}

The problem is that every return statement gets highlighted because cannot return a value from a method with void result type , something I can not understand, because it is clearly defined as a boolean method. 问题是每个return语句都会突出显示,因为cannot return a value from a method with void result type ,这是我无法理解的,因为它明确定义为boolean方法。 I suppose, it has something to do with the new thread I created, but since this app will be running on an Android device, I haveve to run my query in a separate thread. 我想,它与我创建的新线程有关,但由于这个应用程序将在Android设备上运行,我必须在一个单独的线程中运行我的查询。

Thanks in advance! 提前致谢!

All of your code is within the public void run() method, which returns void . 您的所有代码都在public void run()方法中,该方法返回void Therefore returning boolean is not allowed. 因此不允许返回boolean

It is all about scope. 一切都与范围有关。 You can't start a new thread and then return the value from inside the thread scope. 您无法启动新线程,然后从线程范围内返回值。 The run() method inside the Thread class has a void return type. Thread类中的run()方法具有void返回类型。

You would have to remove the thread and then put the code directly in the method. 您必须删除该线程,然后将代码直接放在方法中。 But because it's android, it won't allow connections on main thread, so you have to create a callback interface and once the site is loaded inside the thread, you call a method inside the interface with the result: true or false. 但是因为它是android,它不允许主线程上的连接,所以你必须创建一个回调接口,一旦站点被加载到线程内,你就可以调用接口内的方法,结果为:true或false。

As others have pointed out, the cause of the compilation errors is that you are trying to return a value in the run() method of an anonymous Runnable instance. 正如其他人所指出的,编译错误的原因是你试图在匿名Runnable实例的run()方法中返回一个值。 The run() method is a void method. run()方法是一个void方法。

In a comment, you asked how you could "fix it" so that your login method can return the result. 在评论中,您询问了如何“修复它”,以便您的login方法可以返回结果。

The simple answer is to get rid of the thread and run() method and do the work directly in the login method; 简单的答案是摆脱线程和run()方法,直接在login方法中完成工作; eg 例如

public static boolean login(final String name, final String password) {
    try {
        URL url = new URL("some url");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        // write the post data ...
        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();
        return (responseCode == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

If login has to return a value, then that value needs to be available when the method returns. 如果login必须返回一个值,那么该方法返回时该值必须可用。 It is synchronous. 它是同步的。 If you do the work in a (another) thread, then the current thread has to 1) wait for that other thread to finish, and 2) get the result from that thread. 如果你在(另一个)线程中完成工作,那么当前线程必须1)等待其他线程完成,并且2)从该线程获得结果。 You can do it, but it is pointless. 你可以做到,但没有意义。

If your goal is to avoid blocking the current thread when login is called, then the login method needs to return a Future or something like that. 如果你的目标是在调用login时避免阻塞当前线程,那么login方法需要返回Future或类似的东西。 But ultimately, the code that uses the success / failure status for the login will need to call Future.get . 但最终,使用登录成功/失败状态的代码将需要调用Future.get That may need to wait for the result, and therefore block the thread. 这可能需要等待结果,因此阻塞线程。

The best answer may be to redesign your UI's state machine. 最好的答案可能是重新设计UI的状态机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM