Problem with Toast in AsyncTask method call

余生长醉 提交于 2019-11-28 10:28:04

The code in the doInBackground() method runs on its own thread so you cannot access any UI element from there directly as they are running on the UI thread.

So you got two options.

  1. You handle all the UI stuff in the onPreExecute() and onPostExecute() method which run on the UI thread.

  2. You handle UI stuff in the onProgressUpdate() method which also runs on the UI thread. You can trigger this method from within doInBackground() by calling publishProgress().

you can Toast inside doInBackground

use this code

runOnUiThread(new Runnable() {
public void run() {

    Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show();
    }
});

You are trying to update the UI within doInBackground() which runs in another thread different from the UI thread. You should display the Toast in the onPostExecute() method on your AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

Yeah using a log for debugging is simplest, however if you do have messages that need to be displayed during the background processing for whatever reason, you can use the onProgressUpdate() method, as noted above by Flo. You can trigger this method whenever you need to write a message, by calling publishProgress() from within DoInBackground(). Message content or processing statuses can easily be passed via private variables in the ASyncTask which are accessible to both the Background method and the UI methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!