0

I'm building an application that harvests data from the web. But if there is not a connection, I want to display a message, however if there is a connection I want the program to carry on.

In pseudo code it'd be something like:

if (connection == true) {
   // Get Data
} else {
   // Output error message
}

But how would I actually find out if there is a connection to start with to do this?

mino
  • 6,978
  • 21
  • 62
  • 75
  • 1
    What kind of object is connection? It can't be a `boolean` for sure! – adarshr Feb 22 '12 at 15:37
  • 1
    Check out http://stackoverflow.com/questions/1402005/how-to-check-if-internet-connection-is-present-in-java for possible answers. – Mike Bockus Feb 22 '12 at 15:37
  • that code looks fine to me. what is `connection`? you need to look at the documentation for whatever network/sockets library you're using. it will indicate how to handle failed connection attempts. – ardnew Feb 22 '12 at 15:38
  • There will be no connection, unless you make one. The APIs you use to make one will throw exceptions when something goes wrong. – Ingo Feb 22 '12 at 15:38
  • 'connection' isn't anything. It's just a format I would imagine it taking, I'm asking on here because I don't know how to perform the if-statement. – mino Feb 22 '12 at 15:44

3 Answers3

2

Looking at the tags it is an internet connection, you would just do like this

try {
    //open connection
} catch(Exception e) {
    //connection failed
}
2

If you are connecting to a web address you would probably want to create a URL then call openConnection to get a URLConnection. Now with your URLConnection you can do:

try {
    connection.connect();

    // Get your data here.
} catch (IOException e) {
    // Handle your error message here
}
DaveJohnston
  • 10,031
  • 10
  • 54
  • 83
1

Try comparing connection with null(only if its an object). Like this-

if(connection!=null)
sgowd
  • 2,242
  • 22
  • 29