Posting Toast message from a Thread

前端 未结 4 2132
温柔的废话
温柔的废话 2020-12-03 22:09

My application launches a thread to query the web for some data. I want to display a Toast message when nothing is found, but my application always crashes.

I\'ve t

4条回答
  •  执笔经年
    2020-12-03 22:27

    Toast.makeText().show() definitely needs to be run on the UI thread.

    You should probably use an AsyncTask like Octavian Damiean mentioned, but here's some code using runOnUiThread if you're set on using that:

        public void showToastFromBackground(final String message) {
        runOnUiThread(new Runnable() {
    
            @Override
            public void run() {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        });
    }
    

提交回复
热议问题