I am trying to run the for loop in every half second.The loop is changing something in the view every time it is called,but the changes are made by another class i.e 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();
That's because any view can be only modify in the main thread or ui Thread. Try running onSpeedChanged()
using 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();
You should update the UI Components in runOnUIThread
.Sample code is
runOnUiThread(new Runnable() {
@Override
public void run() {
//stuff that updates ui
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With