Rory Price Rory Price - 7 months ago 103
Java Question

Check HTTP connection to a URL (Android)

I am trying to check a connection to a URL using HTTP in an app...

Process:

User clicks buttons, app sends a get request and then if successful it will return true, else false.

final Button mbutton = (Button) findViewById(R.id.httpcheck);
mbutton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){

public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL("http://www.google.co.uk");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}

}
});


Example

Answer

You are creating a method in your own click instead of calling the method. you should put the isConntectedToServer method in an asynctask and call the AsyncTask in the onClick

final Button mbutton = (Button) findViewById(R.id.httpcheck);
mbutton.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){

      //call asynctask containing isConntectedToServer method here

    }
});

//put this code in an asynctask and call it there
 public boolean isConnectedToServer(String url, int timeout) {
            try{
                URL myUrl = new URL("http://www.google.co.uk");
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(timeout);
                connection.connect();
                return true;
            } catch (Exception e) {
                return false;
            }
        }
Comments