Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Resolve Symbol error when using URL

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?

like image 350
munna ss Avatar asked Nov 28 '22 23:11

munna ss


2 Answers

I encountered the same problem. Just do:

import java.net.URL;
like image 166
quzhi65222714 Avatar answered Dec 04 '22 11:12

quzhi65222714


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();
}
like image 33
hata Avatar answered Dec 04 '22 13:12

hata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!