9

I need a little help with updating my UI from Runnable/Handler every second. I'm using this code :

Runnable runnable = new Runnable() {
        @Override
        public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        prBar.setProgress(myProgress);
                        y = (double) ( (double) myProgress/ (double) RPCCommunicator.totalPackets)*100;
                        txtInfoSync1.setText(Integer.toString((int)y) + "%");
                        prBar.setMax(RPCCommunicator.totalPackets);

                        int tmp = totalBytesReceived - timerSaved;
                        Log.w("","totalBytesReceived : "+totalBytesReceived + " timerSaved : "+timerSaved );
                        Log.w("","tmp : "+tmp);

                        if (avgSpeedCalc.size() > 10)
                        {
                            avgSpeedCalc.remove(0);
                        }

                        avgSpeedCalc.add(tmp);

                        int x = 0;

                        for (int y=0;y<avgSpeedCalc.size();y++)
                        {
                            x += avgSpeedCalc.get(y);
                            Log.d("","x : "+x);
                        }

                        x = Math.round(x/avgSpeedCalc.size());
                        Log.e("","x : "+x);

                        timerSaved = totalBytesReceived;
                        txtSpeed.setText(Integer.toString(x));

                    }
                });
        }
    };

I tried with handler.postDelayed(runnable, 1000); in onCreate(), but the runnable never starts. Or even if I try with runnable.run(); , it's still not working.

Any ideas how can I start runnable/handler and update the ui every second?

Android-Droid
  • 14,365
  • 41
  • 114
  • 185

2 Answers2

33

Why are you creating a runnable in a runnable?

Try this:

// flag that should be set true if handler should stop
boolean mStopHandler = false;

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do your stuff - don't create a new runnable here!
        if (!mStopHandler) {
            mHandler.postDelayed(this, 1000);
        }
    }
};

// start it with:
mHandler.post(runnable);
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
  • and how can I stop it after that? I mean I need this to run only when I'm getting data over internet and I want to stop the runnable after activity finish or user click cancel button. – Android-Droid Feb 06 '12 at 12:24
  • 2
    Actually `handler.removeCallbacks(runnable);` is doing the same thing. – Android-Droid Feb 06 '12 at 12:48
  • Thats true, this is preferable if you delay is long, regarding the 1sec interval it doesn't make a real difference – WarrenFaith Feb 06 '12 at 13:02
  • @WarrenFaith Your runnable will only run once! Right?! What is then the correct way to make it run forever? – Radu May 14 '13 at 13:40
  • 1
    @Radu the current code will run forever. `mStopHandler` is false, so `!mStopHandler` is true and the `postDelayed(this, 1000);` will restart the runnable after 1 second. – WarrenFaith May 14 '13 at 13:50
  • @WarrenFaith Don't you need to make runnable final? – Radu May 14 '13 at 13:55
  • @Radu It depends where you put this code. If you define it outside a method as member variables (except the `mHandler.post(runnable)`, of course), nothing of the used vars need to be final. If you put the complete code in a method, you must make mStopHandler and mHandler final. – WarrenFaith May 14 '13 at 14:00
  • @WarrenFaith How can I restart the same handler after making mStophandler true, or do I need to create another ?? – Abhinav Nov 21 '13 at 09:04
  • @IGOTSAR just make the flag false and call mHandler.post(runnable) again – WarrenFaith Nov 21 '13 at 09:06
  • can the above code be used to toggle between the states of toggle button..? –  Jan 07 '17 at 05:47
5

If you want to update your UI i think this is best option

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do your work
            }
        },500);
Viral Patel
  • 32,418
  • 18
  • 82
  • 110
Sumit
  • 138
  • 1
  • 8
  • can the above code be used to toggle between the states of toggle button..? –  Jan 07 '17 at 05:46