Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android update ui from handler every second

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?

like image 500
Android-Droid Avatar asked Feb 06 '12 12:02

Android-Droid


2 Answers

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);
like image 172
WarrenFaith Avatar answered Nov 08 '22 23:11

WarrenFaith


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);
like image 40
Sumit Avatar answered Nov 09 '22 01:11

Sumit