2

Okay, there must be an easy approach I'm missing here, but I'm drawing a blank. I have a custom ListView that gets some of its images from files on the external storage, some from the internet, and if neither of those it displays a PNG file from the drawable folder. For my logic, I need to be able to tell if a String (image location) is an URL type or File type.

So, how would I be able to tell if a String is in URL format or File format?

chRyNaN
  • 3,592
  • 5
  • 46
  • 74
  • 1
    Couldnt you check the protocol? Like file:// for local and http:// or similar for url? and if local files are of type /mnt/sdcard while urls are of type protocol://domain/path . Is it that hard? – ppsreejith Jan 07 '13 at 00:38
  • That is a possibility, of course, I would have to use something like `Environment.getExternalStorageDirectory().getAbsolutePath()` rather than hard coding `/mnt/sdcard`. `Is it that hard?` - that's a matter of personal perception and is irrelevant to the question asked. – chRyNaN Jan 07 '13 at 00:48

2 Answers2

4

Use URI to try and parse your string:

try {
    new URI(theString);
} catch (URISyntaxException e) {
    // Certainly not an URL
}

You will have to make additional checks, such as checking this URI's scheme (or calling .toURL() on it and check that it does not throw a MalformedURLException).

fge
  • 119,121
  • 33
  • 254
  • 329
  • It looks like checking to see if it throws a `MalformedUrlException` is the best approach. Thanks a lot I appreciate it! – chRyNaN Jan 07 '13 at 00:55
  • Yes, though your answer is more in-depth, the general concept is the same and the accepted answer was first. However, I gave you a +1 for the detail. Thanks! – chRyNaN Jan 07 '13 at 01:09
0

A malformed URL will give you an exception. To know if you the URL is active or not you have to perform a handshake with the URL.

There is no other way that I know of.

syb0rg
  • 8,057
  • 9
  • 41
  • 81