1

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?

Yitian Zhang
  • 314
  • 1
  • 3
  • 18

4 Answers4

2

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

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
0

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
}
Ivan Fontalvo
  • 433
  • 4
  • 21
  • I've tried this but the method I use to send the message doesn't throw a ConnectionException. However, sometimes when the client doesn't have the correct server ip or can't connect for any reason, it will throw a ConnectionException. So I want to check to make sure that if it does throw this error, the button doesn't click. –  Oct 22 '18 at 15:42
0

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
    }
}
Yitian Zhang
  • 314
  • 1
  • 3
  • 18
Engrtunze
  • 30
  • 1
  • 1
  • 7
0

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();
         }
     }
}
Yitian Zhang
  • 314
  • 1
  • 3
  • 18
Engrtunze
  • 30
  • 1
  • 1
  • 7