2

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

Community
  • 1
  • 1
Rory Price
  • 45
  • 1
  • 1
  • 6

2 Answers2

4

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;
            }
        }
Parnit
  • 1,032
  • 2
  • 8
  • 16
  • How do I use a asynctask? Any help would be really appreciated – Rory Price Mar 16 '14 at 22:49
  • I suggest reading the android developer link i have pasted here. http://developer.android.com/reference/android/os/AsyncTask.html. It will provide all the details on asynctask with an example on how to use it. In a nut shell, an asynctask has 2 main parts: 1. doInBackground method to make a network call to execute a function or get data (where you will use your IsConnectedToServer method) and 2. onPostExecute to store data and update the UI thread. – Parnit Mar 16 '14 at 23:19
  • This always produce exception of NetworkOnMainthread exception – EngineSense Nov 17 '16 at 07:30
0

Here you can find an answer of a similar question. You just have to change the function to make your function return a boolean. Hope that helps you.

Test an HTTP connection

Joan Gil
  • 282
  • 3
  • 11