java 使用 URL 时无法解决符号错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32294795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot Resolve Symbol error when using URL
提问by munna ss
class background_thread extends AsyncTask<String ,String , Boolean > {
protected Boolean doInBackground(String... params) {
String UR = "127.0.0.1/abc/index.php";
try {
URL url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
}
}
When I use the above code, in the HttpURLConnection the url turns red and Android Studio is showing an error can not resolve symbol url. What's wrong with the code?
当我使用上面的代码时,在 HttpURLConnection 中 url 变为红色并且 Android Studio 显示错误无法解析符号 url。代码有什么问题?
回答by quzhi65222714
I encountered the same problem. Just do:
我遇到了同样的问题。做就是了:
import java.net.URL;
回答by hata
Put the line which is openning connection inside of try
clause:
将打开连接的行放在try
子句中:
try {
URL url = new URL(UR);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
It is because the valiable url
is a local one which is valid only inside the try
clause.
这是因为变量url
是局部变量,仅在try
子句内部有效。
Or declair the url
outside of the try
clause:
或声明子句的url
外部try
:
URL url;
try {
url = new URL(UR);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
With Java 7+, we can use the AutoClosablefeature:
在 Java 7+ 中,我们可以使用AutoClosable功能:
URL url;
try {
url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try (HttpURLConnection conn = (HttpURLConnection) url.openConnection())
// Do something...
} catch (IOException e) {
e.printStackTrace();
}
回答by josedlujan
Sometimes you need a asimple 'gradlew clean'
有时你需要一个简单的“gradlew clean”
"Click" on "Build"->"Clean Project" and that will perform a gradle clean
Or:
或者:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
回答by knack
Adding
添加
import java.net.MalformedURLException;
solve the missing resolve symbol.
解决缺少的解析符号。
You must of course have this too:
你当然也必须有这个:
import java.net.URL;