javaandroidconnectionexception

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


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?


Solution

  • 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();
             }
         }
    }