how to show toast in Runnable class on Java, Android? [closed]
I have a class implements Runnable interface, and I need show Toast from this class. How can I do that?
You can make use of handlers to display a Toast. Because few things in Android must be done from UI thread only. Try this,
Do this in your onCreate(),
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progressDialog.cancel();
if (msg.what == 0) {
Toast.makeText(Catering.this,"Hi toast",Toast.LENGTH_LONG).show();
}
}};
And now your thread,
final Thread Fetcher = new Thread(new Runnable() {
public void run() {
handler.sendEmptyMessage(0);
});
Fetcher.start();
The issue isn't whether or not it implements Runnable. The issue is that it has to be run by the main display thread, and will need access to the Activity's context. If you paste your code, we can help you fix it.
I think you are getting error because you are creating and showing Toast from a NON-GUI thread. You can only write to the display from the GUI thread. Post your code for us to help you further.
I think you want to do as like:
current class:
take a contex's object
and pass contex.this to implemented class's constructor.
in that constructor you should write:
this.context1 = context;
at the toast showing you should pass context1.
i think this will help you.
精彩评论