I am facing some problems when I\'m using Toast inside run method of Thread class.
My error Logcat
09-16 11:42:38.140: E/AndroidRuntime(1446): in wri
You need to call toast inside onPostExecute()
method
@Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show();
}
You've to call the Toast on UI thread.
AsyncTask onPostExecute runs on UI thread. If you want to "force" a UI thread, you can use the following code inside onBackground:
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(....).show();
}
});
According to your logcat
you are trying to update UI part (using Toast)
in doInBackground()
of AsyncTask
which is not possible directly
Use same in onPostExecute()
which is used for handling/updating UI Part
If you want to show Toast in doInbackground()
wrap the Toast in runOnUIThread()
but this isn't the best solution.
like
runOnUiThread(new Runnable() {
@Override
public void run() {
// Show Toast Here
}
});
You may display your Toast message as below:
YourActivityName.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(YourActivityName.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}
});
By calling an Activity's runOnUiThread method from your Thread:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Toast message inside Thread", Toast.LENGTH_LONG).show();
}
});
You can not use or access any UI elements inside a non UI thread. If you want to see some messages about your thread then you may use AsyncTask and use the UI stuffs inside preExecute method.because the pre and postExecute of AsyncTask are run on UI thread.
If you want to do like so then see Problem with Toast in AsyncTask method call .
If you are excepting a small and easy way, then just use LOG class like:
Log.d("String Key", "the value you want to see");
If you want some ideas about log then please see Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?
Hope these are sufficient for your question.