Android "Only the original thread that created the view hierarchy can touch its views." error for loop

I try to run a for loop in every half second. The loop changes something in the view every time it is called, but changes are made by another class ie Speedometer.

Thread thread=new Thread(){ @Override public void run() { float i; try { for ( i = 0; i <= 100; i++) { Speedometer1.onSpeedChanged(Speedometer1.getCurrentSpeed(i) + 8); Speedometer2.onSpeedChanged(Speedometer2.getCurrentSpeed(i) + 8); Speedometer3.onSpeedChanged(Speedometer3.getCurrentSpeed(i) + 8); Speedometer4.onSpeedChanged(Speedometer4.getCurrentSpeed(i) + 8); Speedometer5.onSpeedChanged(Speedometer5.getCurrentSpeed(i) + 8); Speedometer6.onSpeedChanged(Speedometer6.getCurrentSpeed(i) + 8); sleep(500); } } catch (InterruptedException e) {e.printStackTrace();} } };thread.start(); 
+6
source share
4 answers

This is because any representation can only be changed in the main thread or in the thread. Try running onSpeedChanged() with runOnUiThread() . Like this:

  Thread thread=new Thread(){ @Override public void run() { float i; try { for ( i = 0; i <= 100; i++) { runOnUiThread(new Runnable() { public void run() { Speedometer1.onSpeedChanged(Speedometer1.getCurrentSpeed(i) + 8); Speedometer2.onSpeedChanged(Speedometer2.getCurrentSpeed(i) + 8); Speedometer3.onSpeedChanged(Speedometer3.getCurrentSpeed(i) + 8); Speedometer4.onSpeedChanged(Speedometer4.getCurrentSpeed(i) + 8); Speedometer5.onSpeedChanged(Speedometer5.getCurrentSpeed(i) + 8); Speedometer6.onSpeedChanged(Speedometer6.getCurrentSpeed(i) + 8) } }); sleep(500); } } catch (InterruptedException e) {e.printStackTrace();} } };thread.start(); 
+9
source

You must update the user interface components in runOnUIThread . Sample code

 runOnUiThread(new Runnable() { @Override public void run() { //stuff that updates ui } }); 
+6
source

You must update your user interface in the user interface thread.

To do this, create a handler in the onCreate () method:

 private Handler mHandler; @Override public void onCreate() { mHandler = new Handler(); // ... } 

Then call the handler in a separate thread to execute it in the main thread:

 mHandler.post(new Runnable() { @Override public void run() { // Update your UI } }); 
+3
source

You cannot modify View objects outside the main thread. Although your Speedometer class Speedometer making changes, it starts in the secondary thread that you created.

You can create a Runnable and submit using deejay to a Handler created by the main thread, or use other similar methods to achieve the same.

0
source

All Articles