Search code examples
androidmultithreadingexceptiontcptoast

I cant see my Toast messages in new Thread(new Runnable()


I have a little problem with displaying messages after connection and disconection.

I am trying when press my connection button and establish communication in new Thread to get toast message: You are connected and also if I am not connected to get the toast in the exception:You are not connected.

I tried to replace new Thread with

runOnUiThread(new Runnable() /*but then It underline*/}).start(); at the end of my code as a mistake.When I delete start and run the app it cant connect to my server.

I tried many solutions but none of them works.I will be very appreciative If you can help me.

 @Override
  public void onClick(View v) {

    new Thread(new Runnable() {
        @Override
        public void run() {
          try {
            server = serverTxt.getText().toString();
                Socket socket = new Socket(server, port);
                socket.setSoTimeout(30000);
                connected = true;
                Toast.makeText(getApplicationContext(), "You are connected",Toast.LENGTH_LONG).show();
            //send the message to the server
                here = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            } catch (Exception e) {
                  Toast.makeText(getApplicationContext(), "You are not connected",Toast.LENGTH_LONG).show();
            }
        }
     }).start();
    }
   });

Solution

  • You have to use runOnUiThread as follows:

    DO NOT TRY TO USE SOCKET PART IN UI THREAD, IT WILL THROW AN EXCEPTION

    new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        server = serverTxt.getText().toString();
            Socket socket = new Socket(server, port);
            socket.setSoTimeout(30000);
            connected = true;
    
         //if inside a fragment, call with getActivity().runOnUiThread()
         Activity.this.runOnUiThread(new Runnable(){
    
            public void run(){
    
                Toast.makeText(getApplicationContext(), "You are connected",Toast.LENGTH_LONG).show();
    
            }
         });
        //send the message to the server
            here = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    
        } catch (Exception e) {
    
         //if inside a fragment, call with getActivity().runOnUiThread()
         Activity.this.runOnUiThread(new Runnable(){
    
            public void run(){
    
                Toast.makeText(getApplicationContext(), "You are not connected",Toast.LENGTH_LONG).show();
    
            }
         });
    
        }
    }
    
    }).start();
    

    runOnUiThread is a method. .start() works only on Thread objects and is used to start a new thread. here you want your ui(already running) thread to take focus :)