How to show toast in AsyncTask in doInBackground

后端 未结 9 718
灰色年华
灰色年华 2020-11-27 23:01

In one of my activities I\'m using AsyncTask. In doInBackground() I\'m making calls to various methods. In one of these methods I\'m getting an exc

相关标签:
9条回答
  • 2020-11-27 23:16

    Create a handler object and execute all your Toast messages using that.

    @Override
    protected Void doInBackground(Void... params) {
    
        Handler handler=new handler();
        handler=  new Handler(context.getMainLooper());
        handler.post( new Runnable(){
            public void run(){
                Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
            }
        });
      }
    
    0 讨论(0)
  • 2020-11-27 23:18

    try this code

    void showError(final String err) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG)
                        .show();
            }
        });
      }
    
    0 讨论(0)
  • 2020-11-27 23:26

    If you have to declare anything related to Thread, then it must be outside the runOnUiThread() method, then only it is going to execute,

        @Override
        protected String doInBackground(String... strings) {
            for(int i=0; i<10; i++) {
    
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Example for Toast "+i, Toast.LENGTH_SHORT).show();
                    }
                });
    
                try {
                    Thread.sleep(10);
                } catch (Exception e) {}
            }
    
            return "";
        }
    
    0 讨论(0)
  • 2020-11-27 23:27

    Write the following code where you have to show toast in doInBackground() method

    runOnUiThread(new Runnable() {
    
    public void run() {
    
      Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();
    
       }
    });
    
    • BTW: if you are using Fragments, you need to call runOnUiThread(...) through your activity:

    getActivity().runOnUiThread(...)

    0 讨论(0)
  • 2020-11-27 23:30

    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.

    0 讨论(0)
  • 2020-11-27 23:31

    You can display it in a method, that has access to the UI thread like onPreExecute(), onProgressUpdate() and onPostExecute()

    0 讨论(0)
提交回复
热议问题