Shan
Shan

Reputation: 2832

How to display a Toast inside a Handler/thread?

I want to display a toast once the message is sent to a socket.After this "Log.d("ClientActivity", "C: Sent.");"

Whether I need to create a separate thread to display Toast?

public class ClientActivity extends Activity {
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.client);
    serverIp = (EditText) findViewById(R.id.EditText01);
    message =(EditText) findViewById(R.id.EditText02);
    connectPhones = (Button) findViewById(R.id.Button01);

}

    public void Click1(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }


private class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
            connected = true;
            while (connected) {
                try {
                    if(i>5)
                    {


                    } 
                    else
                    {   
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands
                        message1= message.getText().toString();
                        out.println(message1);
                        i=i+1;
                        Log.d("ClientActivity", "C: Sent.");
                    }    
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

}

Upvotes: 8

Views: 23392

Answers (4)

itechDroid
itechDroid

Reputation: 1031

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        System.out.println("I'm in handler");
        Toast.makeText(YourActivity.this, "This is a toast", Toast.LENGTH_SHORT).show(); 
    }
}, 1000);             

Upvotes: 3

Ashwin
Ashwin

Reputation: 13537

You cannot create a toast from inside a thread. Because this new thread does not have access to the getApplicationContext() that you pass on to it. You somehow have to establesh a communication with the UI thread(i.e the main thread).
So whenever you want to toast something do it in the handler.Post(Runnable) method. Handler is the middle man between the UI thread and the separate thread that you are running. All UI Operations will have to be done in handler.Post(Runnable)'s run() method.

So in your activity to display a toast do this :

private class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
             .....
             .....
              message1= message.getText().toString();
                        out.println(message1);
                        i=i+1;
                        Log.d("ClientActivity", "C: Sent.");
                        handler.post(new Runnable(){
                          public void run()
                          {
                             Toast.make(....);
                           }
                         });

Don't forget to declare and initialize a handler object in your main activity(outside the thread)

handler=new Handler();

Upvotes: 3

Andro Selva
Andro Selva

Reputation: 54322

Declare a global Handler first,

Handler handler=null;

Then Create a handler in your onCreate() like this,

Handler handler=new Handler()
{
  public void handleMessage(Message msg)
{
  if(msg.what==0)
{
   Toast.makeText(ClientActivity.this,"Your Toast Mesage Goes here",Toast.LENGTH_LONG).show();
}

}
};

And now in your Runnable class add this line after "Log.d("ClientActivity", "C: Sent.");"

handler.sendEmptyMessage(0);

The problem you are facing is because you can't update UI from runnable. Handlers connect you to your main UI. So you have to pass a message to your handler from your Runnable.

Upvotes: 1

5hssba
5hssba

Reputation: 8079

put

  runOnUiThread(new Runnable() {
                 public void run() {

                     Toast.makeText(ClientActivity.this,"asdf",Toast.LENGTH_LONG).show();
                }
            });

after this line

  Log.d("ClientActivity", "C: Connecting...");

Upvotes: 22

Related Questions