How To Display A Toast Inside A Handler/thread?
Solution 1:
put
runOnUiThread(new Runnable() {
publicvoidrun() {
Toast.makeText(ClientActivity.this,"asdf",Toast.LENGTH_LONG).show();
}
});
after this line
Log.d("ClientActivity", "C: Connecting...");
Solution 2:
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 :
privateclassClientThreadimplementsRunnable {
publicvoidrun() {
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(){
publicvoidrun()
{
Toast.make(....);
}
});
Don't forget to declare and initialize a handler object in your main activity(outside the thread)
handler=new Handler();
Solution 3:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
publicvoidrun() {
System.out.println("I'm in handler");
Toast.makeText(YourActivity.this, "This is a toast", Toast.LENGTH_SHORT).show();
}
}, 1000);
Solution 4:
Declare a global Handler first,
Handler handler=null;
Then Create a handler in your onCreate() like this,
Handler handler=new Handler()
{
publicvoidhandleMessage(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.
Post a Comment for "How To Display A Toast Inside A Handler/thread?"