![](/img/trans.png)
[英]Catching and rethrowing an exception from a boolean method does return false whereas not doing anything causes the method not to return
[英]Boolean method can not return anything
我正在开发一个Android应用程序,现在我正在为登录系统编写一些方法。 我试图创建一个boolean
方法,根据服务器的响应返回true或false。 这是我的代码:
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();
}
问题是每个return语句都会突出显示,因为cannot return a value from a method with void result type
,这是我无法理解的,因为它明确定义为boolean
方法。 我想,它与我创建的新线程有关,但由于这个应用程序将在Android设备上运行,我必须在一个单独的线程中运行我的查询。
提前致谢!
您的所有代码都在public void run()
方法中,该方法返回void
。 因此不允许返回boolean
。
一切都与范围有关。 您无法启动新线程,然后从线程范围内返回值。 Thread类中的run()
方法具有void返回类型。
您必须删除该线程,然后将代码直接放在方法中。 但是因为它是android,它不允许主线程上的连接,所以你必须创建一个回调接口,一旦站点被加载到线程内,你就可以调用接口内的方法,结果为:true或false。
正如其他人所指出的,编译错误的原因是你试图在匿名Runnable
实例的run()
方法中返回一个值。 run()
方法是一个void方法。
在评论中,您询问了如何“修复它”,以便您的login
方法可以返回结果。
简单的答案是摆脱线程和run()
方法,直接在login
方法中完成工作; 例如
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;
}
}
如果login
必须返回一个值,那么该方法返回时该值必须可用。 它是同步的。 如果你在(另一个)线程中完成工作,那么当前线程必须1)等待其他线程完成,并且2)从该线程获得结果。 你可以做到,但没有意义。
如果你的目标是在调用login
时避免阻塞当前线程,那么login
方法需要返回Future
或类似的东西。 但最终,使用登录成功/失败状态的代码将需要调用Future.get
。 这可能需要等待结果,因此阻塞线程。
最好的答案可能是重新设计UI的状态机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.