Problem with Toast in AsyncTask method call

前端 未结 4 985
故里飘歌
故里飘歌 2020-12-10 08:54

Hey Everybody,
I have an AsyncTask that posts some data to a server. It does this by calling a static method that I wrote from doInBackground. When I run the AsyncTask,

相关标签:
4条回答
  • 2020-12-10 09:16

    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.

    0 讨论(0)
  • 2020-12-10 09:31

    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().

    0 讨论(0)
  • 2020-12-10 09:34

    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)

    0 讨论(0)
  • 2020-12-10 09:40

    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();
        }
    });
    
    0 讨论(0)
提交回复
热议问题