0

I am developing an Android app and in that I have a countdown timer which onFinish() does this -

double initial_time = 0.0;
double countup;

public void onFinish() {
                    startTimer();
                }

         public void startTimer(){
        //Start the scheduled timer
        Log.d("hi","crash app 0");
        Early_Delay_Display.setText(R.string.Departure_Delay);
        rootView.invalidate();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        Log.d("hi","crash app 1" + initial_time);
                        countup = 0.0 + initial_time;
                        Log.d("hi","crash app 2" + initial_time + "---------" + countup);
                        Early_Delay_Time.setText(String.valueOf(countup));
                        rootView.invalidate();
                        initial_time = initial_time + 0.5;
                    }
                },
                1000, 30000//delay,period
        );
    }

Basically using this timer, I want to display 0.5,1.0,1.5 for every 30 seconds but the app crashes.

The logs are -

crash app 0
crash app 1 0.0
crash app 2 0.0---------0.0

After this the app crashes

Samuel909
  • 13
  • 5

3 Answers3

0

There's special CountDownTimer in android, so you can just use it like mentioned here

Community
  • 1
  • 1
Silwester
  • 418
  • 5
  • 12
  • My question is not about countdown timer. It is about the timer which is different from countdown timer. My countdown timer works well – Samuel909 Jul 05 '16 at 11:03
  • @Samuel909 why do you do it onFinish() then? what is the point? I guess you're accessing the view, which was already destroyed: rootView – Silwester Jul 05 '16 at 11:38
0

I guess your activity is destroyed and then timer makes your app crash.

user6547359
  • 204
  • 1
  • 9
0

I found out the answer. You can never update the UI froma thread. Instead you could do this -

public void startUpCounting(){
        //Start the scheduled timer
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                countup = 0.0 + initial_time;
                Log.d("hi","crash app 2" + initial_time + "---------" + countup);
                mHandler.obtainMessage(1).sendToTarget();
                initial_time = initial_time + 0.5;
            }
        }, 0, 1000);
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Early_Delay_Time.setText(String.valueOf(countup));
            rootView.invalidate();
        }
    };
Samuel909
  • 13
  • 5