Sean O
Sean O

Reputation: 236

How can I create a time counter in android studio?

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.

Upvotes: 0

Views: 8140

Answers (3)

Marcel
Marcel

Reputation: 173

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);
    }
}
}

Upvotes: 0

Arsal Imam
Arsal Imam

Reputation: 2992

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.

Upvotes: 2

oemel09
oemel09

Reputation: 763

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.

Upvotes: 0

Related Questions