javaandroidscopehandlers

Updating a number in a TextView every second


I'm writing my first app in which I need to update the number in a text view every second until a button is pressed. Using a handler seems to be impossible because the number is created and stored outside of the handler, but it can't be declared final because it needs to change. Thread.sleepalso seems to make the app hang indefinitely, before some code is executed that is written above it.

final TextView countView = (TextView) findViewById(R.id.counter);
        countView.setText("100,000,000,000");

    //set a Calendar object to be 00:00:00:00 on Jan 1, 2015
    final Calendar startTime = Calendar.getInstance();
    startTime.set(2015, 0, 0, 12, 0, 0);
    startTime.set(Calendar.MILLISECOND, 0);

final Button startButton = (Button) findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //set a Calendar to be the time that the button is clicked and find the difference in ms between it and startTime
                Calendar nowTime = Calendar.getInstance();
                double milStart = startTime.getTimeInMillis();
                double milNow = nowTime.getTimeInMillis();
                double diff = (milNow-milStart)/1000;     //difference in seconds between "start" date and current date

                double total = 100000000000L;   //# that needs to be updated
                for(long i = 0L; i < diff; i++) {
                    total += 1.8;
                }
                countView.setText(NumberFormat.getInstance().format(total));

I need to continue to increment total by 1.8 every second or by 1 every 556 milliseconds.

while(true) {
   countView.setText(NumberFormat.getInstance().format(total));
   total += 1.8;
   try {
      Thread.sleep(1000);
       } catch (InterruptedException e) {}
 } 

Causes the app to hang indefinitely as soon as the button is clicked, so that even the first countView.setText(NumberFormat.getInstance().format(total)); doesn't execute.

Using a handler doesn't seem possible to me since total can't work if declared final, but creating a variable inside the handler and looping it would cause the value to never change.

Am I missing an obvious solution? This is my first real endeavor with Java so it's all new to me


Solution

  • you may use Handler

    Handler h = new Handler();
    final Runnable r = new Runnable() {
            int count = 0;
            @Override
            public void run() {
                count++;
                textView.setText(""+count*1.8);
                h.postDelayed(this, 1000); //ms
            }
        };
    h.postDelayed(r, 1000); // one second in ms
    

    for stopping you may use h.removeCallbacksAndMessages(null);