How to show toast in AsyncTask in doInBackground
You could wrap the Toast in runOnUIThread()
but this isn't the best solution.
You should set a boolean flag in the catch block when an error occurs, then display an appropriate Toast in onProgressUpdate()
, onPostExecute()
, or any of the other methods with UI access whenever the flag is true
.
How to display a Toast in Android AsyncTask?
You cannot update UI on background thread. doInBackground()
is invoked on the background thread. You should update UI on the UI thread.
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui here
// display toast here
}
});
onPreExecute()
, onPostExecute(Result)
, are invoked on the UI thread. So you can display toast here.
onProgressUpdate(Progress...)
, invoked on the UI thread after a call to publishProgress(Progress...)
can be used to animate a progress bar or show logs in a text field.
The result of doInBackground()
computation is a parameter to onPostExecute(Result)
so return the result in doinBackground()
and show your toast in onPostExecute(Result)
You can also use a handler as suggested by @Stine Pike
For clarity, check the link below under the topic: The 4 steps.
http://developer.android.com/reference/android/os/AsyncTask.html
How to raise a toast in AsyncTask, I am prompted to used the Looper
onPostExecute - executes on UI thread
or
publishProgress()
; in your doinbackground and
protected void onProgressUpdate(Integer... progress) {
}
http://developer.android.com/reference/android/os/AsyncTask.html
How to display toast in AsyncTask
Supposing MyAsync is nested in an Activity :
private class myAsync extends AsyncTask<Void, Integer, Void>
{
int duration = 0;
int current = 0;
int inc = 0;
@Override
protected Void doInBackground(Void... params) {
videoView.start();
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
duration = videoView.getDuration();
}
});
do {
current = videoView.getCurrentPosition();
inc = inc + 1;
if(inc == 10000 || inc == 25000 || inc == 30000){
showToast(inc);
}
} while (current <= duration);
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
showToast(values[0]);
// Todo integrate gravity parameter
}
private void showToast(String text)
{
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
});
}
}
How to show toast in AsyncTask in doInBackground
You could wrap the Toast in runOnUIThread()
but this isn't the best solution.
You should set a boolean flag in the catch block when an error occurs, then display an appropriate Toast in onProgressUpdate()
, onPostExecute()
, or any of the other methods with UI access whenever the flag is true
.
How can I show a Toast from AsyncTask onPostExecute?
public class MyTask extends AsyncTask<Void, Void, Void>{
private Context mContext;
public MyTask(Context context){
mContext = context;
}
...
...
protected void onPostUpdate(Integer... progress){
Toast toast= Toast.makeText(mContext, "Loaded A-Z", Toast.LENGTH_LONG);
toast.show();
}
}
and instantiate it like so:
MyTask task = new MyTask(MyActivity.this).execute();
This is how I do AsyncTask's that require arguments, I also define callbacks this way in the constructor of the Tasks to interact with the activities that call them.
Showing a Toast message from AsyncTask using Kotlin
Pass an instance of Context
to DownloadChapters
when you instantiate it and use it in onPostExecute
. Make sure it's an applicationContext
, to avoid accidentally leaking your Activity.
class DownloadChapters(private val context: Context) : AsyncTask<String, Void, String>() {
override fun onPostExecute(result: String) {
super.onPostExecute(result)
Toast.makeText(context, result , Toast.LENGTH_SHORT).show()
}
}
// In Activity
DownloadChapters(applicationContext).execute(currentChapUrl)
Better yet, replace your AsyncTask with Coroutines. AsyncTask is deprecated.
Android: toast inside AsyncTask
I'm going t close this question. I haven't solved my problem but the number of answers provided that apparently work in other situations suggest there's something else going on. I'm going to re-structure the classes to get around having to call from within AsyncTask.
Related Topics
How Does Native Android Code Written for Arm Run on X86
Proguard with Ormlite on Android
Touch and Drag Image in Android
Android Listview Row Delete Animation
Android: Notifydatasetchanged(); Not Working
Google Maps Fragment Returning Null Inside a Fragment
Adding Your Own SQLite Database to an Android Application
Parse JSON Array Response Using Retrofit & Gson
How to Launch Front Camera with Intent
Android Datepicker Min Max Date Before API Level 11
Android Sms Receiver Not Working
Find Current Location Latitude and Longitude in Android
What Is Setcontentview(R.Layout.Main)
How to Implement My Own Disk Cache with Picasso Library - Android