当我有异常时在doInBackground中显示Toast

时间:2013-11-22 11:04:17

标签: android android-asynctask toast android-toast

我想在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,因为这段代码没有出现。

2 个答案:

答案 0 :(得分:3)

  

当我有异常时在doInBackground中显示Toast

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

你需要纠正你的方法!现在它不会覆盖超类方法。十,你传递的方法是1,所以你需要纠正你的方法。

该方法必须如下所示:

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

现在它应该有效。

请仔细查看AsyncTask docs

答案 1 :(得分:0)

将日志放入doInBackground本身,但使用Handlers来执行此操作。

handler.post(new Runnable() {

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