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?
I encountered the same problem. Just do:
import java.net.URL;
Put the line which is openning connection inside of try
clause:
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.
Or declair the url
outside of the try
clause:
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 AutoClosable feature:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With