【问题标题】:How to create toast in android inside asyntask [duplicate]如何在异步任务中的android中创建吐司[重复]
【发布时间】:2016-03-29 17:55:46
【问题描述】:

我已经这样做了:

doInBackground(String... prams){
    Toast.makeText(getApplicationContext(),
                            "Server too busy. Please try after sometime.",
                            Toast.LENGTH_LONG).show();}

出现错误。请帮忙。

【问题讨论】:

  • 你遇到了什么错误?
  • 你遇到了什么错误?
  • 这 - 12-23 15:45:30.548: W/System.err(3596): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  • 在 onPostExecute() 中添加该行
  • 出现错误时代码崩溃,onPostExecute() 未调用。

标签: android android-asynctask


【解决方案1】:

您无法在 doInBackground 中更新 UI。执行此操作以显示 toast

getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Server too busy. Please try after sometime.",
                        Toast.LENGTH_LONG).show();

            }
        });

它会解决你的问题

【讨论】:

  • 为什么会发生。Toast 在 Asyctask 中不起作用,在 runOnUiThread 中起作用
  • 因为 Toast 在 Ui 线程上运行并且 Async 任务启动新线程所以它给出了异常
【解决方案2】:

你不能在里面显示吐司

doInBackground(String... prams){}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 2012-11-06
    • 1970-01-01
    相关资源
    最近更新 更多