I searched many places but could not find a complete working example of implementation of "runOnUiThread". I tried a lot , but getting lots of errors . I just want to display a toast from a thread.
Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.
A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.
Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()
Creating a Toast Toast toast = Toast. makeText(getApplicationContext(), "This is a message displayed in a Toast", Toast. LENGTH_SHORT); toast. show();
So here is the final full code. Thanks to all who have replied.
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MainActivity.this.runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show(); } }); } }
And About the XML, its is the default XML file created. No change needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With