To Examples

StopWatch Example

Goal:

Directions:

  1. Create an Android project with name Stopwatch and Empty Activity. Leave the Java activity file name as MainActivity.java and leave the layout file name as activity_main.xml.
  2. Change the layout to LinearLayout.
  3. Set these properties in the layout:

    Attribute Value
    layout_width match_parent
    layout_height match_parent
    orientation vertical
    padding 16dp
  4. Add a text view to display the time and three buttons with these attributes:

    Attribute TextView Button1 Button2 Button3
    id txt_time      
    layout_width wrap_content wrap_content wrap_content wrap_content
    layout_height wrap_content wrap_content wrap_content wrap_content
    layout_gravity center_horizontal center_horizontal center_horizontal center_horizontal
    layout_marginTop   20dp 8dp 8dp
    textSize 80sp 80sp 25sp 25sp
    text 0:00:00 Start Stop Reset
    onClick   onClickStart onClickStop onClickReset
  5. Extract the strings in the layout to the strings.xml resource file:

    String Name String Value
    start_time 0:00:00
    start_caption Start
    stop_caption Stop
    reset_caption reset
  6. Run the app to test the layout.
  7. Here are the layout and activity files so far:
            activity_main.xml  strings.xml
  8. Make these additions to the MainActivity class in the MainActivity.java file:
    1. Define an int instance variable named seconds, initialized to 0.
    2. Define a boolean instance variable named running, initialized to false.
    3. Add these event handlers, corresponding to the buttons, to the MainActivity class:
      public void onClickStart(View view) {
          running = true;
      }
      
      public void onClickStop(View view) {
          running = false;
      }
      
      public void onClickReset(View view) {
          running = false;
          seconds = 0;
      }
      
    4. Add this runTimer method to the MainActivity class:
      private void runTimer( ) {
          final TextView timeView = findViewById(R.id.time);
          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 formattedTime = String.format(
                         "%d:%02d:%02d", hours, minutes, secs);
                  timeView.setText(formattedTime);
                  if (running) {
                      seconds++;
                  }
                  handler.postDelayed(this, 1000);
              }
          });
      }
      
    5. Add a runTimer( ); statement to the onCreate event handler.
    6. Run the app to test it.
    7. Rotate the app 90 degrees. You see that the layout changes from portrait to landscapt and the time gets set back to 0:00:00. This is because the activity is destroyed when the app is rotated. We need to save the values of the seconds and running variables so we can restore them when the activity resumes after the device is rotated. As in the ClickCounter Example, if the layout does not change from portrait to landscape and back, go to the emulator Settings >> Display and set Auto-rotate Screen to On.
    8. Here is the activity code so far:
          MainActivity.java
  9. Make these additions to the java activity code:
    1. Add this instance variable declaration with comment at the top of the StopwatchActivity class:
      // Was the stopwatch running before the activity was paused?
      private boolean wasRunning;
      
    2. Add these lines to the onCreate event handler before the runTimer( ) method call:
      if (savedInstanceState != null) {
          seconds = savedInstanceState.getInt("seconds");
          running = savedInstanceState.getBoolean("running");
          wasRunning = savedInstanceState.getBoolean("wasRunning");
      }
      
    3. Add these event handlers after the onCreate method:
      @Override
      public void onSaveInstanceState(Bundle savedInstanceState) {
          super.onSaveInstanceState(savedInstanceState);
          savedInstanceState.putInt("seconds", seconds);
          savedInstanceState.putBoolean("running", running);
          savedInstanceState.putBoolean("wasRunning", wasRunning);
      }
      
      @Override
      protected void onPause( ) {
          super.onPause( );
          wasRunning = running;
          running = false;
      }
      
      @Override
      protected void onResume( ) {
          super.onResume( );
          if (wasRunning( )) {
              running = true;
          }
      }
      
    4. The final activity file: MainActivity.java.