Using the Run Dialog Using 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(); 

The main function of showdialog show, but on the line where ShowManager () is called, is getting an 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 modifies the elements of a view. briefly something like

  public void ShowManager() { TextView mainText = (TextView) findViewById(R.id.wifiText); mainText.setText("editted"); } 
+4
source share
4 answers

I have found the answer. I do not like to answer my own question, but perhaps this one will help someone else. We cannot update most user interface objects in a separate thread. We need to 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(); 
+13
source

use this instead of just loaddialog.dismiss ()

 runOnUiThread(new Runnable() { @Override public void run() { loadingdialog.dismiss(); } }); 
+4
source

This is because you are trying to reject the dialog from the stream while it was created in the main user interface thread. Try moving the ProgressDialog.show statement inside the stream. I would prefer to use AsyncTask, since they are much easier to manage, as in this

0
source

something like this is normal:

 public void startScan() { new Thread() { public void run() { loadingdialog = ProgressDialog.show(WifiManagementActivity.this, "","Scanning Please Wait",true); try { sleep(4000); ShowManager(); } catch(Exception e) { Log.e("threadmessage",e.getMessage()); } loadingdialog.dismiss(); } }.start(); } 

note the position of ProgressDialog.show (...), here in the thread that invokes the dialog, dialog.dismiss () is called. but the cleanest way to achieve this using AsynTask

0
source

Source: https://habr.com/ru/post/1389845/


All Articles