How to check if an Connection Error occurs using an if statement

84 Views Asked by At

So I have a button that sends a message to a server when i press it. However, I want to make sure that if there is a ConnectionException the button wont click and will return a Toast.

button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         if (v.getId() == R.id.button) {
              //Send Message to Server
         } else 
             Toast.makeText(getApplicationContext(), "Server hasn't connected", Toast.LENGTH_LONG).show();
     }
}

I was just wondering how I might implement this?

4

There are 4 best solutions below

1
Engrtunze On BEST ANSWER

try this first

button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         try{
             if (v.getId() == R.id.button) {
                  //Send Message to Server
             }else {
                  throw new serverExceptionerror ("Server hasn't connected"); 
             } 
         }
         catch (serverExceptionerror ex) { 
             Toast.makeText(ex.getMessage(),Toast.LENGTH_LONG).show();
         }
     }
}
1
Ivalberto On

In this case , you should use a try-catch statement.

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}
0
Ilya Gazman On

Button clicks happening on the UI thread, the main thread, while server communication is happening on IO thread, non-main thread. You need to have a model that will tell you if an error happened and then display your error message.

One possible solution is to use an AsyncTask

0
Engrtunze On

wrap you code with a try and catch statment. eg.

button.setOnClickListener(new View.OnClickListener() {
    @Override
    try
    {
        public void onClick(View v) {
            if (v.getId() == R.id.button) {
                 //Send Message to Server
            } else
                 Toast.makeText(getApplicationContext(), "Server hasn't connected", Toast.LENGTH_LONG).show();
            }
        }
    }
    catch(exception (type) e)
    {
        //your custom message
    }
}