Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android “Only the original thread that created a view hierarchy can touch its views.” error in for loop [duplicate]

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();
like image 705
Ariel Avatar asked Aug 03 '16 12:08

Ariel


2 Answers

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();
like image 186
Miguel Benitez Avatar answered Sep 23 '22 08:09

Miguel Benitez


You should update the UI Components in runOnUIThread.Sample code is

runOnUiThread(new Runnable() {
     @Override
     public void run() {

       //stuff that updates ui

    }
});
like image 23
Mujammil Ahamed Avatar answered Sep 24 '22 08:09

Mujammil Ahamed