【问题标题】:Display Toast in doInBackground when I have exception当我有异常时在 doInBackground 中显示 Toast
【发布时间】:2013-11-22 11:04:17
【问题描述】:

我想在 doInBackground 方法的后台线程中显示一个 Toast。当然,这是行不通的。所以我尝试了这个

int error = 1;
publishProgress(error);
Log.i ( "InternetConnection" , "Loading Internet from Cache not working because of no Internet connection." );
return null;

而onProgressUpdate方法是

protected void onProgressUpdate ( Integer integers ){
    if ( integers == 1){
        Toast.makeText ( c.getApplicationContext(), "Daten konnten nicht geladen werden.", 0).show();
    }
}

是不是,当我调用 publishProgress 时使用了 onProgressUpdate ?

C 是我的活动,所以

Context c = MainActivity();

我怎么可能显示 Toast,因为这段代码没有显示出来。

【问题讨论】:

  • 使用日志,或将数据发送到 postExecute 以显示在 ui 上
  • 我正在登录。对于看不到日志的用户,它应该是可见的。敬酒是我想做的事。不想将其作为静态文本显示给用户。
  • @Rohit 您可以在 onProgressUpdate() 方法中处理 UI 内容,该方法也运行在 UI 线程上。

标签: android android-asynctask toast android-toast


【解决方案1】:

出现异常时在 doInBackground 中显示 Toast

onProgressUpdate() 方法采用 T 对象数组(通常),在您的情况下为 整数数组

您需要更正您的方法!现在它不是覆盖超类方法。十,您将传递给此方法编号 1,因此您需要更正您的方法。

该方法必须如下所示:

protected void onProgressUpdate(Integer... integers) {
    int value = integers[0];
   if (value == 1) {
      // show your Toast    
   }
}

现在应该可以了。

请仔细查看AsyncTask docs

【讨论】:

    【解决方案2】:

    将日志放入 doInBackground 本身,但使用 Handlers 这样做。

    handler.post(new Runnable() {
    
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                   //your logs here.
                                }
                            });
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 2014-03-08
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2016-06-15
      相关资源
      最近更新 更多