0

I'm trying to put a timer that begins at 0 on my app, and counts from 0 (seconds) changing from (1... 13... 59... 1:19, etc), and then ends pauses, or stops when the game ends. I want to be able to display this paused time to show how long it took for the user to finish playing.

I've tried the chronometer method(?) but it kept crashing the app and didn't work. Currently am trying to use thread t = new thread... but not having any luck.

1 of my tries

Thread t = new Thread(){@Override
            public void run(){
                try{
                    while(!isInterrupted()){
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TextView textViewTime = findViewById(R.id.textTimer);
                                long time = System.currentTimeMillis();
                                textViewTime.setText(time);
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
        t.start();

Currently have 'time' underlined saying cannot resolve method setText(long) I've shamelessly tried created this counter re-using code from a different project but for that project I was used a SimpleDateFormat method so it was slightly easier.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Sean O
  • 238
  • 3
  • 14
  • This is not the correct implementation for this purpose, android offers CountDownTimer API for this purposes. – Arsal Imam Jun 17 '19 at 17:41
  • Look at this example for an Android Timer: [Android Timer Example](https://stackoverflow.com/questions/4597690/android-timer-how-to) – Marcel Jun 17 '19 at 17:55

3 Answers3

2

Android offers CountDownTimer API to perform these operations, check the example below,

long maxCounter = 30000;
long diff = 1000;

    new CountDownTimer(maxCounter , diff ) {

        public void onTick(long millisUntilFinished) {
            long diff = maxCounter - millisUntilFinished;
            mTextField.setText("seconds completed: " +diff  / 1000);
           //here you can have your logic to set text to edittext
        }

        public void onFinish() {
            mTextField.setText("done!");
        }

    }.start();

EDIT:

I have updated my answer to use as upward counter.

Arsal Imam
  • 2,882
  • 2
  • 24
  • 35
  • Thanks! But sadly, I require a timer that counts upwards and not down. Purely for using time as an attribute to calculate points later on. – Sean O Jun 17 '19 at 17:48
0

The setText() method of TextView does only accept Strings, that's why the compiler throws an error in this line. Use Long.toString(time) to display the time in a TextView.
As the time is in millis you probably would want to convert it so seconds by using this snippet:

textViewTime.setText(Long.toString(time / 1000));

I also recommend you to do the initialisation of the TextView
TextView textViewTime = findViewById(R.id.textTimer);
earlier in your code, as it doesn't need to be part of the loop.

oemel09
  • 744
  • 7
  • 15
  • Thanks for the help. I've corrected the code as you've said but the app is still crashing. I'm creating the app in a separate class called GameView that extends View, but this thread t = new thread is currently in my MainActivity that extends AppCompactActivity. Any idea if the different location is why its crashing the app? – Sean O Jun 17 '19 at 17:43
  • Nevermind, got the app to stop crashing! The timer is appearing, but its showing '156079419'... not sure why. – Sean O Jun 17 '19 at 17:56
  • Ah well, actually you don't need the System.currentTimeMillis(). Just create a time variable and add one second each time. – oemel09 Jun 17 '19 at 18:05
0

Below is an example for an Android Timer. The Runnable shows the Timer in the format 0:00. Example 0:18 or 3:42. The button stops the Timer.

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends AppCompatActivity implements View.OnClickListener {

private long starttime = 0;
private TextView tvTimer;
private Button btnEndTimer;
private Handler timerHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);

    tvTimer = findViewById(R.id.tvTimer);
    btnEndTimer = findViewById(R.id.btnEndTimer);
    btnEndTimer.setOnClickListener(this);

    starttime = System.currentTimeMillis();
    timerHandler.postDelayed(timer, 0);
}

protected void onStop() {
    super.onStop();
    timerHandler.removeCallbacks(timer);
}

private Runnable timer = new Runnable() {
    @Override
    public void run() {
        long millis = System.currentTimeMillis() - starttime;
        int seconds = (int) (millis / 1000);
        int minutes = seconds / 60;
        seconds %= 60;
        tvTimer.setText(String.format("%d:%02d", minutes, seconds));

        timerHandler.postDelayed(this, 500);
    }
};

@Override
public void onClick(View v) {
    if (v.getId() == R.id.btnEndTimer) {
        timerHandler.removeCallbacks(timer);
    }
}
}
Marcel
  • 173
  • 3
  • 8