0

I have been trying to build a stopwatch in my app which starts counting on a start button click.I want it to count from seconds then minutes, then Hour but the problem is I can't count Hour but I can count milliseconds which I do not want. is that possible on start button click the app takes the current system time and on stop click just calculate and print the interval between starts and stop clicks?

Here is my activity class

package com.example.rimapps.stopwatch;

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

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button but1,but2;
    long MillisecondTIme,StarTime,TimeBuff,UpdateTime=0L;
    Handler handler;
    int MilliSeconds,Seconds,Minutes,Hour;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=(TextView)findViewById(R.id.textView);
        but1=(Button)findViewById(R.id.buttonstart);
        but2=(Button)findViewById(R.id.buttonstop);

        handler = new Handler();

        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Date d=new Date();
                //SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
                //String currentDateTimeString=sdf.format(d);
                //textView.setText(currentDateTimeString);

                StarTime=SystemClock.uptimeMillis();
                handler.postDelayed(runnable,0);
                //reset.setEnabled(false);

            }

        });
        but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MillisecondTIme=0L;

                TimeBuff = 0L ;
                UpdateTime = 0L ;
                Seconds = 0 ;
                Minutes = 0 ;
                MilliSeconds = 0 ;
                textView.setText("00:00:00");

            }
        });

    }
    public Runnable runnable=new Runnable() {
        @Override
        public void run() {
            MillisecondTIme=SystemClock.uptimeMillis()-StarTime;
            UpdateTime=TimeBuff+MillisecondTIme;
            Seconds=(int)(UpdateTime/1000);
            Minutes=Seconds/60;
            Seconds=Seconds%60;
            MilliSeconds=(int)(UpdateTime%1000);

            textView.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));
            handler.postDelayed(this,0);

        }
    };

}

here is my xml layout

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.rimapps.stopwatch.MainActivity">

        <TextView
            android:text="00:00:00"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:textSize="50dp"
            android:textStyle="bold"
            android:textColor="#009688"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="33dp" />

        <Button
            android:text="Start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="47dp"
            android:id="@+id/buttonstart"
            android:layout_below="@+id/textView"
            android:layout_alignLeft="@+id/textView"
            android:layout_alignStart="@+id/textView" />
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">

            <Button
                android:text="Stop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/buttonstop"

                android:layout_marginRight="89dp"
                android:layout_marginEnd="89dp"
                android:layout_marginTop="140dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

        </RelativeLayout>
    </RelativeLayout>
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Please explain why you don't just add Hours = 0; to initialize Hours....and then add Hours = Minutes /60; ?? Are you trying to also show fractional hours for some reason? Please explain in more detail.. – Dr t Nov 20 '17 at 16:48

2 Answers2

0

While I was learning a book I also had a stopwatch coding problem this is a sample of the code I use.

final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                int hours=seconds/3600;
                int minutes=(seconds%3600)/60;
                int secs=seconds%60;
                String time = String.format("%d:%02d:%02d",hours,minutes,secs);
                timeView.setText(time);
                if(running)
                {
                    seconds++;
                }
                handler.postDelayed(this,1000);
            }
        });

also understand Handler class, handler will always run the code immediately(like every second forever) so you gotta add a boolean value that know if it is running then set it to your button like if start button is click you got to set the running to true. Handler will always run forever like the famous loop() method of arduino(it is running forever).

0xDEADBEEF
  • 590
  • 1
  • 5
  • 16
0

Use sendMessage that does have a clearMessage instead of postRunnable

This time I'll write for you (most for fix convention with camel case):

The stop function is at the second button action listener

package com.example.rimapps.stopwatch;

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

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button but1,but2;
    long millisecondTIme,starTime,timeBuff,updateTime=0L;
    Handler handler;
    int milliSeconds,seconds,minutes,hour;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=(TextView)findViewById(R.id.textView);
        but1=(Button)findViewById(R.id.buttonstart);
        but2=(Button)findViewById(R.id.buttonstop);

        handler = new Handler() {
             public void handleMessage(Message what) {
                millisecondTIme=SystemClock.uptimeMillis()-starTime;
                updateTime=timeBuff+millisecondTIme;
                seconds=(int)(UpdateTime/1000);
                minutes=Seconds/60;
                seconds=Seconds%60;
                milliSeconds=(int)(updateTime%1000);

                textView.setText("" + minutes + ":"
                        + String.format("%02d", seconds) + ":"
                        + String.format("%03d", milliSeconds));
                handler.sendEmptyMessageDelayed(0, 1000); //repost in a loop
             }
        }

        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                starTime=SystemClock.uptimeMillis();
                handler.sendEmptyMessage(0); //Here send message with id 0
            }

        });
        but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                millisecondTIme=0L;

                timeBuff = 0L ;
                updateTime = 0L ;
                seconds = 0 ;
                minutes = 0 ;
                milliSeconds = 0 ;
                textView.setText("00:00:00");
                handler.removeMessages(0); //Here clear all messages with same id

            }
        });
    }

}
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • There's an error like this wrong ""1st argument type found :'android.os.Handler' in statement handler.postDelayed(this, 1000);'",,,,, and another one is it cannot resolve handler.clearMessages(); can you pls help – mohamed rimshadpcs Nov 21 '17 at 04:41
  • fixed the code, you had to send another message again delayed, and clear is instead remove – Marcos Vasconcelos Nov 21 '17 at 14:25