1

I've this portion of code:

/**
 * Checks if the provided URL is valid.
 *
 * @param urlToCheck - The URL to check.
 *
 * @return boolean true if it's valid.
 */
protected boolean isUrlValid( String urlToCheck )
{
    boolean isValid = true;
    try
    {
        URL url = new URL( urlToCheck );
    }
    catch ( MalformedURLException exception )
    {
        isValid = false;
    }

    return isValid;
}

As you can see, I'm creating a new URL Object, which crashes if the String URL is not valid. This is working, the "problem" is that LINT says I'm not using url variable. I don't really have to use it, so here's my question:

  • Is there any other better approach?
  • Can I supress lint checking JUST for this line?
Reinherd
  • 5,476
  • 7
  • 51
  • 88

4 Answers4

5

You see a warning because you are not using the variable and probably wasting memory. If you dont need the variable you can do something like this

protected boolean isUrlValid( String urlToCheck )
{
    boolean isValid = true;
    try
    {
        new URL( urlToCheck ); // Notice this
    }
    catch ( MalformedURLException exception )
    {
        isValid = false;
    }

    return isValid;
}
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
4

There's nothing wrong about doing that, however your variable is not used.

You can change

URL url = new URL( urlToCheck );

to

new URL( urlToCheck );
Eel Lee
  • 3,513
  • 2
  • 31
  • 49
1

You can replace

URL url = new URL( urlToCheck );

with something like this:

new URL( urlToCheck );

This will ensure that you do not have any unused reference pointing to the URL object. Thus the compiler will not complain.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

In reverse order:

  • You can get rid of the warning by not creating a new variable, as others have pointed (use only new Url(urlToCheck);

but maybe the better aproach is to:

  • use URLUtil.isValidUrl(String url) - looking at it's source I see it doesn't create a new url variable which might be better, but it looks like it just checks whether the string starts with a known scheme. It's up to you to decide whether this is enough
stan0
  • 11,549
  • 6
  • 42
  • 59