Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress Dialog usage with Thread

here is my code,

public ProgressDialog loadingdialog;
public void ShowManager() {
    //do something
}
public void startScan() {
      loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
                                              "","Scanning Please Wait",true);
      new Thread() {
          public void run() {
              try {
                    sleep(4000);
                    ShowManager();

              } catch(Exception e) {
                    Log.e("threadmessage",e.getMessage());
              }
              loadingdialog.dismiss();
          }
      }.start();
    }

startScan();

A basic progressdialog show function, but on the line where ShowManager() is called, getting error ,

01-07 23:11:36.081: ERROR/threadmessage(576): Only the original thread 
that created a view hierarchy can touch its views.

EDIT:

ShowManager() is a function that change the view elements. shortly something like,

  public void ShowManager() 
  {
      TextView mainText = (TextView) findViewById(R.id.wifiText);
      mainText.setText("editted");

  }
like image 633
Okan Kocyigit Avatar asked Dec 03 '22 00:12

Okan Kocyigit


1 Answers

I found the answer. I don't like to answer my own question but maybe this will help someone else. We cannot update most UI objects while in a separate thread. We must create a handler and update the view inside it.

public ProgressDialog loadingdialog;
  private Handler handler = new Handler() {
          @Override
              public void handleMessage(Message msg) {
              loadingdialog.dismiss();
              ShowManager();

          }
      };
  public void ShowManager()
  {
      TextView mainText = (TextView) findViewById(R.id.wifiText);
      mainText.setText("editted");
  }
  public void startScan() {
      loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
                                          "","Scanning Please Wait",true);
      new Thread() {
          public void run() {
              try {
                  sleep(4000);
                  handler.sendEmptyMessage(0);

              } catch(Exception e) {
                  Log.e("threadmessage",e.getMessage());
              }
          }
      }.start();
  }

  startScan();
like image 86
Okan Kocyigit Avatar answered Dec 26 '22 15:12

Okan Kocyigit