StopWatch Android App Project - Part 3

This the final part in our series of making a Stopwatch Android App in android studio and this is one of the most important part in this project.

If you haven't followed the previous two parts, please do before going forward with this:

In this part we will write the login for all the features of stopwatch to make the app work according to our needs. So before going to the coding part we have to know some basic things as shown below:

  1. 1 second = 1000 millisecond

  2. 1 minute = 60 second

  3. 1 hour =60 minute

Stopwatch Android App - Code the Logic

Now open the MainActivity.java file and import some basic classes as shown below:

//importing required classes
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Locale;

Next we create the object of Android ImageView and Android Textview inside MainActivity class as shown below:

//creating object of ImageView and Text View
ImageView playBtn, pauseBtn, stopBtn, timeLapseBtn;
TextView timeView;
TextView timeViewms;
TextView timeLapse;

Next we add come integer variable and boolean variable as ashow below inside MainActivity.java class:

// integers to store hours, minutes, seconds,  ms 
int hours, minutes, secs, ms;

// integer to store seconds
private int seconds = 0;

// boolean to check if the stopwatch is running or not
private boolean running;

// simple count variable to count number of laps
int lapCount=0;

Now inside the onCreate method we initialize the ImageView and TextView and add the OnClickListener and show a simple Android Toast message to the user according to the input as shown below:

// initializing the Image view objects
playBtn=(ImageView)findViewById(R.id.playBtn) ;
pauseBtn=(ImageView)findViewById(R.id.pauseBtn) ;
stopBtn=(ImageView)findViewById(R.id.stopBtn) ;

timeLapseBtn=(ImageView)findViewById(R.id.timeLapseBtn) ;

// initializing the text view objects
timeView = (TextView)findViewById(R.id.time_view) ;
timeViewms=(TextView)findViewById(R.id.time_view_ms) ;
timeLapse = (TextView)findViewById(R.id.timeLapse) ;

  // play button click listener
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //showing simple toast message to user
                Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show(); 

                // hide the play and stop button
                playBtn.setVisibility(View.GONE) ;
                stopBtn.setVisibility(View.GONE) ;

                // show the pause  and time lapse button
                pauseBtn.setVisibility(View.VISIBLE) ;
                timeLapseBtn.setVisibility(View.VISIBLE) ;

                // set running true
                running = true ;
            }
        }) ;
        // pause button click listener
        pauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //showing simple toast message to user
                Toast.makeText(MainActivity.this, "Paused", Toast.LENGTH_SHORT).show();

                // show the play  and stop  button
                playBtn.setVisibility(View.VISIBLE) ;
                stopBtn.setVisibility(View.VISIBLE) ;
                
                // hide the pause  and time lapse button
                timeLapseBtn.setVisibility(View.GONE) ;
                pauseBtn.setVisibility(View.GONE) ;

                running = false ;
            }
        }) ;

        // stop  button click listener
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //showing simple toast message to user
                Toast.makeText(MainActivity.this, "Stoped", Toast.LENGTH_SHORT).show();

                // set running to false
                running = false ;
                seconds = 0 ;
                lapCount=0 ;
                
                // setting the text view to zero
                timeView.setText("00:00:00") ;
                timeViewms.setText("00") ;
                timeLapse.setText("") ;

                // show the play  
                playBtn.setVisibility(View.VISIBLE) ;
                
                // hide the pause , stop and time lapse button
                pauseBtn.setVisibility(View.GONE) ;
                stopBtn.setVisibility(View.GONE) ;
                timeLapseBtn.setVisibility(View.GONE) ;
            }
        }) ;

        // lap button click listener
        timeLapseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // calling timeLapse function
                timeLapseFun() ;
            }
        }) ;

// calling runtimer
runTimer() ;

Now inside create a method private void runTimer which is called when we click the start button as shown below:

private void runTimer() {

	// creating handler
	final Handler handlertime = new Handler();

	// creating handler
	final Handler handlerMs = new Handler();

	handlertime.post(new Runnable() {@Override

		public void run() {
			hours = seconds / 3600;
			minutes = (seconds % 3600) / 60;
			secs = seconds % 60;

			// if running increment the seconds
			if (running) {
				String time = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs);

				timeView.setText(time);

				seconds++;
			}

			handlertime.postDelayed(this, 1000);
		}
	});

	handlerMs.post(new Runnable() {@Override
		public void run() {

			if (ms >= 99) {
				ms = 0;
			}

			// if running increment the ms
			if (running) {
				String msString = String.format(Locale.getDefault(), "%02d", ms);
				timeViewms.setText(msString);

				ms++;
			}
			handlerMs.postDelayed(this, 1);
		}
	});

}

We create one more method inside the MainActivity.java to handle lap time as shown below:

void timeLapseFun() {

	// increase lap count when function is called
	lapCount++;

	String laptext = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs);
	String msString = String.format(Locale.getDefault(), "%02d", ms);

	// adding ms to lap text
	laptext = laptext + ":" + msString;

	if (lapCount >= 10) {
		laptext = " Lap " + lapCount + " ------------->       " + laptext + " \n " + timeLapse.getText();
	} else {
		laptext = " Lap " + lapCount + " --------------->       " + laptext + " \n " + timeLapse.getText();

	}

	//showing simple toast message to user
	Toast.makeText(MainActivity.this, "Lap " + lapCount, Toast.LENGTH_SHORT).show();

	// showing the lap text
	timeLapse.setText(laptext);
}

The complete code of the MainActivity.java is shown below:

package com.studytonight.project;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

// importing required classes
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

	// integers to store hours , minutes , seconds ,  ms 
	int hours,
	minutes,
	secs,
	ms;

	// integer to store seconds
	private int seconds = 0;

	// boolean to check if stopwatch is running or not
	private boolean running;

	// simple count variable to count number of laps
	int lapCount = 0;

	// creating object of ImageView and Text View
	ImageView playBtn,
	pauseBtn,
	stopBtn,
	timeLapseBtn;
	TextView timeView;
	TextView timeViewms;
	TextView timeLapse;

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

		// initializing the Image view objects
		playBtn = (ImageView) findViewById(R.id.playBtn);
		pauseBtn = (ImageView) findViewById(R.id.pauseBtn);
		stopBtn = (ImageView) findViewById(R.id.stopBtn);

		timeLapseBtn = (ImageView) findViewById(R.id.timeLapseBtn);

		// initializing the text view objects
		timeView = (TextView) findViewById(R.id.time_view);
		timeViewms = (TextView) findViewById(R.id.time_view_ms);
		timeLapse = (TextView) findViewById(R.id.timeLapse);

		// play button click listener
		playBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {

				//showing simple toast message to user
				Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();

				// hide the play and stop button
				playBtn.setVisibility(View.GONE);
				stopBtn.setVisibility(View.GONE);

				// show the pause  and time lapse button
				pauseBtn.setVisibility(View.VISIBLE);
				timeLapseBtn.setVisibility(View.VISIBLE);

				// set running true
				running = true;
			}
		});
		// pause button click listener
		pauseBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {

				//showing simple toast message to user
				Toast.makeText(MainActivity.this, "Paused", Toast.LENGTH_SHORT).show();

				// show the play  and stop  button
				playBtn.setVisibility(View.VISIBLE);
				stopBtn.setVisibility(View.VISIBLE);

				// hide the pause  and time lapse button
				timeLapseBtn.setVisibility(View.GONE);
				pauseBtn.setVisibility(View.GONE);

				running = false;
			}
		});

		// stop  button click listener
		stopBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {

				//showing simple toast message to user
				Toast.makeText(MainActivity.this, "Stoped", Toast.LENGTH_SHORT).show();

				// set running to false
				running = false;
				seconds = 0;
				lapCount = 0;

				// setting the text view to zero
				timeView.setText("00:00:00");
				timeViewms.setText("00");
				timeLapse.setText("");

				// show the play
				playBtn.setVisibility(View.VISIBLE);

				// hide the pause , stop and time lapse button
				pauseBtn.setVisibility(View.GONE);
				stopBtn.setVisibility(View.GONE);
				timeLapseBtn.setVisibility(View.GONE);

			}
		});

		// lap button click listener
		timeLapseBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {
				// calling timeLapse function
				timeLapseFun();
			}
		});

		// calling runtimer
		runTimer();

	}

	private void runTimer() {

		// creating handler
		final Handler handlertime = new Handler();

		// creating handler
		final Handler handlerMs = new Handler();

		handlertime.post(new Runnable() {@Override

			public void run() {
				hours = seconds / 3600;
				minutes = (seconds % 3600) / 60;
				secs = seconds % 60;

				// if running increment the seconds
				if (running) {
					String time = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs);

					timeView.setText(time);

					seconds++;
				}

				handlertime.postDelayed(this, 1000);
			}
		});

		handlerMs.post(new Runnable() {@Override
			public void run() {

				if (ms >= 99) {
					ms = 0;
				}

				// if running increment the ms
				if (running) {
					String msString = String.format(Locale.getDefault(), "%02d", ms);
					timeViewms.setText(msString);

					ms++;
				}
				handlerMs.postDelayed(this, 1);
			}
		});

	}

	void timeLapseFun() {

		// increase lap count when function is called
		lapCount++;

		String laptext = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs);
		String msString = String.format(Locale.getDefault(), "%02d", ms);

		// adding ms to lap text
		laptext = laptext + ":" + msString;

		if (lapCount >= 10) {
			laptext = " Lap " + lapCount + " ------------->       " + laptext + " \n " + timeLapse.getText();
		} else {
			laptext = " Lap " + lapCount + " --------------->       " + laptext + " \n " + timeLapse.getText();

		}

		//showing simple toast message to user
		Toast.makeText(MainActivity.this, "Lap " + lapCount, Toast.LENGTH_SHORT).show();

		// showing the lap text
		timeLapse.setText(laptext);
	}
}

Output:

In the below snapshots, you can see how the Stopwatch will look in the android application.

When App is opened first time:

stopwatch android app project

When we click on start:


stopwatch android app project

When we click the pause:

stopwatch android app project

When we click on lap icon (we have recorded 12 laps)

stopwatch android app project

When we click on stop icon:

stopwatch android app project

Conclusion:

And with this we have successfully completed the Stopwatch project. If this project helped you then find us on Instagram - @study.tonight and share with us snapshots of your project. Congratulations on finishing the project.