android:取消进度条捕获异常:android.view.ViewRoot $ CalledFromWrongThreadException

时间:2011-03-31 11:52:39

标签: android progress-bar

我正在尝试在我的应用程序中实现进度条。 单击按钮时可以看到此进度条,然后一个线程也随之启动。当线程完成时,我试图使progressBar不可见。但它在排除问题时遇到了异常:

progressbar.setVisibility(View.GONE);

例外:

android.view.ViewRoot $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

我的代码是:

  Thread thredUpdate   = new Thread()
  {
     public void run()
     {
        ClearDatabase();
                 progressbar.setVisibility(View.GONE);                                      
     }
  };
  requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  setProgressBarVisibility(true);
  ProgressBar progressbar  = (ProgressBar)findViewById(R.id.progress);
  progressbar .setVisibility(View.GONE);
  btnUpdateDB.setOnClickListener(new OnClickListener()
  {
      @Override
      public void onClick(View argBtnUpdateDB)
      {                 
            setProgressBarVisibility(true);
            progressbar.setVisibility(View.VISIBLE);
             try
            {
                     if((progressbar.isEnabled()))
                    thredUpdate.start();
             }               
            catch(Exception exSoap) 
            {                                                                                 
                   exSoap.printStackTrace();
            }

  } });

如何在不调用setVisibility(View.GONE)的情况下取消此进度条?

谢谢...

3 个答案:

答案 0 :(得分:4)

您应该从UI线程调用它:

runOnUiThread(new Runnable() {
        public void run() {
             progressbar.setVisibility(View.GONE);
        }
    });

另一种方法是使用AsyncTask代替常规Thread

答案 1 :(得分:1)

你必须用runnable

来调用它
static Handler handler = new Handler();
...

handler.post(hideprogress);


...

static Runnable hideprogress = new Runnable()
    {
        @Override
        public void run() {
            progressbar.setVisibility(View.GONE);
        }
    };

答案 2 :(得分:0)

您可以使用Handler隐藏进度条:

private static final int HANDLER_MESSAGE_UPDATE_COMPLETE = 0;

Thread thredUpdate   = new Thread()
{
    public void run()
    {
        ClearDatabase();
            Message msg = Message.obtain();
            msg.what = HANDLER_MESSAGE_UPDATE_COMPLETE;
            myHandler.sendMessage(msg);                                          
    }
};

Handler myHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case HANDLER_MESSAGE_UPDATE_COMPLETE:
            progressbar.setVisibility(View.GONE);
            break;
        default:
            Log.w("MY_TAG","message type not supported: " + msg.what);
        }
    }
};

此方法使您能够轻松添加新消息类型以处理将来的更改。它还将您的所有UI更新保存在一个位置,以便于维护。