A very simple stoper

So 2 days ago I’ve started learning Android technology. I’ve written very simple program which can count a time using CountDownTimer class. Here is my xml code:

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
tools:context=".MainActivity"
android:id="@+id/raf">

<Button
    android:id="@+id/btnStart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="28dp"
    android:textColor="#76EE00"
    android:background="#2C3529"
    android:text="Start" />

<Button
    android:id="@+id/btnStop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="28dp"
    android:textColor="#76EE00"
    android:background="#2C3529"
    android:text="Stop" />


<TextView
    android:id="@+id/textViewHours"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="25dp"
    android:layout_below="@+id/btnStart"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="20dp"
    android:textColor="#76EE00"
    android:textSize="25sp"
    android:text="Godziny:"
    />

<TextView
    android:id="@+id/textViewMinutes"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="100dp"
    android:layout_below="@+id/textViewHours"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="20dp"
    android:textColor="#76EE00"
    android:textSize="25sp"
    android:text="Minuty:"
    />

<TextView
    android:id="@+id/textViewSeconds"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="100dp"
    android:layout_below="@+id/textViewMinutes"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="20dp"
    android:textColor="#76EE00"
    android:textSize="25sp"
    android:text="Sekundy:"
    />

<TextView
    android:id="@+id/textViewTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/btnStop"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="17dp"
    android:textColor="#76EE00"
    android:textSize="25sp"
    />

<EditText
    android:id="@+id/editHours"
    android:numeric="integer"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/btnStop"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="220dp"
    android:layout_marginTop="35dp"
    android:text="1"
    android:background="#2C3529"
    android:textColor="#76EE00"
    />

<EditText
    android:id="@+id/editMinutes"
    android:numeric="integer"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editHours"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="220dp"
    android:layout_marginTop="30dp"
    android:text="0"
    android:background="#2C3529"
    android:textColor="#76EE00"
    />

<EditText
    android:id="@+id/editSeconds"
    android:numeric="integer"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editMinutes"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="220dp"
    android:layout_marginTop="30dp"
    android:text="0"
    android:background="#2C3529"
    android:textColor="#76EE00"
    />

And here we have java code:

   package com.example.rafa.minutnik;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressLint("NewApi")

public class MainActivity extends ActionBarActivity {

    private Button btnStart,btnStop;
    private TextView textViewTime;
    private EditText editHours, editMinutes, editSeconds;
    private int Time;

    public void reset(){
        editHours.setText("");
        editMinutes.setText("");
        editSeconds.setText("");
        textViewTime.setText("");
    }

    @Override
    public View findViewById(int id) {
        return super.findViewById(id);
    }

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

        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);
        textViewTime = (TextView) findViewById(R.id.textViewTime);
        editHours = (EditText) findViewById(R.id.editHours);
        editMinutes = (EditText) findViewById(R.id.editMinutes);
        editSeconds = (EditText) findViewById(R.id.editSeconds);

        Time = 3600*Integer.parseInt(editHours.getText().toString()) +
                60*Integer.parseInt(editMinutes.getText().toString()) +
                Integer.parseInt(editSeconds.getText().toString());

        final CounterClass timer = new CounterClass(1000*Time,1000);

        btnStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                timer.start();
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                timer.cancel();
                reset();
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer{

        public CounterClass(long milisInFuture, long countDownInterval){

            super(milisInFuture,countDownInterval);
        }

        @TargetApi(Build.VERSION_CODES.KITKAT)
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {

            long milis = millisUntilFinished;
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(milis),
            TimeUnit.MILLISECONDS.toMinutes(milis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milis)),
            TimeUnit.MILLISECONDS.toSeconds(milis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milis)));

            System.out.println(hms);
            textViewTime.setText(hms);
        }

        @Override
        public void onFinish() {

            textViewTime.setText("Finished.");
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

But there is one big drawback, it can count only time from beginning value which is fixed. As you can see I put new edittext fields to change values of hours,minutes and seconds but it doesn’t work and I completely have no idea why.

Any suggestion what did I do wrong?

Answer

Your timer is fixed in the beginning value because are not initializing time value aging in click event of start button, that’s why timer is taking its initial value.

Hope this class will clarify this, replace this onCreate method snippet in your Java class here I changed your start click event also replace reset method

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

    btnStart = (Button) findViewById(R.id.btnStart);
    btnStop = (Button) findViewById(R.id.btnStop);
    textViewTime = (TextView) findViewById(R.id.textViewTime);
    editHours = (EditText) findViewById(R.id.editHours);
    editMinutes = (EditText) findViewById(R.id.editMinutes);
    editSeconds = (EditText) findViewById(R.id.editSeconds);

    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Time = 3600 * Integer.parseInt(editHours.getText().toString())
                    + 60
                    * Integer.parseInt(editMinutes.getText().toString())
                    + Integer.parseInt(editSeconds.getText().toString());

            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            timer = new CounterClass(1000 * Time, 1000);

            timer.start();
        }
    });

    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            timer.cancel();
            reset();
        }
    });
}
public void reset() {
    if (timer != null) {
        timer.cancel();
    }
    editHours.setText("0");
    editMinutes.setText("0");
    editSeconds.setText("0");
    textViewTime.setText("0");
}

Leave a Reply

Your email address will not be published. Required fields are marked *