Practice Calculator Application

In this session we are going to use all the things that we have practiced and build a simple calculator using ViewGroups in an Activity. Let's try building app and run in our phone.

1. New application

  • Create a new application as com.yourname.simplecalulator.
  • Choose empty activity which will show as MainActivity and activity_main.xml.
  • Let the gradle to build for a while.

2. Create calculator in layout.

  • Change parent layout as ScrollView from ConstraintLayout.
  • Inside the ScrollView make a `ConstraintLayout.
  • Add two EditText with id as numberInputOne and numberInputTwo.
  • Below those EditText add a horizontal LinearLayout with weightSum as 3.
  • Add three Buttons inside that LinearLayout with each layout_weight as 1.
  • Buttons should have id as add, subtract and multiply.
  • This will arrange buttons spread out in the linear layout.
  • Create a TextView as id result which will show the results.

activity_main.xml will look something like this

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


  <androidx.constraintlayout.widget.ConstraintLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">


    <EditText
        android:inputType="number"
        android:id="@+id/numberOne"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_width="100dp"
        android:layout_height="wrap_content"/>


    <EditText
        android:inputType="number"
        android:id="@+id/numberTwo"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@id/numberOne"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_width="100dp"
        android:layout_height="wrap_content"/>



    <LinearLayout
        android:layout_marginHorizontal="10dp"
        android:orientation="horizontal"
        android:id="@+id/buttonsHolder"
        android:weightSum="3"
        android:layout_marginTop="50dp"
        app:layout_constraintTop_toBottomOf="@id/numberTwo"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

      <Button
          android:layout_marginHorizontal="5dp"
          android:text="ADD"
          android:layout_weight="1"
          android:id="@+id/add"
          android:layout_width="0dp"
          android:layout_height="wrap_content"/>

      <Button
          android:layout_marginHorizontal="5dp"
          android:text="Subtract"
          android:layout_weight="1"
          android:id="@+id/subtract"
          android:layout_width="0dp"
          android:layout_height="wrap_content"/>

      <Button
          android:layout_marginHorizontal="5dp"
          android:text="Multiply"
          android:layout_weight="1"
          android:id="@+id/multiply"
          android:layout_width="0dp"
          android:layout_height="wrap_content"/>


    </LinearLayout>



    <TextView
        android:layout_marginHorizontal="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="50dp"
        app:layout_constraintTop_toBottomOf="@id/buttonsHolder"
        android:textAlignment="center"
        android:text="Result Here"
        android:id="@+id/result"
        android:textSize="22sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

  </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>

3. Initialization of the ViewGroups/Views we need to work with

  • Initialize the two EditText
  • Initialize the three Buttons
  • Initialize the result TextView
  • Add ClickListeners to each buttons

4. Concept of functions

So we will be creating some methods/functions which will be aiding us in doing some mathematical process over some numbers and will be returning what we need from them. Lets list them

A. Function to add two number and return a integer result as addTwoNumbers(int a, int b)

B. Function to find the difference between two given numbers as subtractTwoNumbers(int a, int b)

C. Function to get product between two numbers as multiplyTwoNumbers(int a, int b)

D. Function that converts string to int and return the int.

E. Function that converts int to string and return the string.

5. Process of value passing

For adding two numbers we will

  • get the numbers as string from the EditText
  • convert them into int using function D
  • get addition result using function A.
  • display the output with the help of E

Sample MainActivity.java code

package com.kushagra.learningmad;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText numberOne, numberTwo;
    Button add, subtract, multiply;
    TextView resultView;

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


        numberOne = findViewById(R.id.numberOne);
        numberTwo = findViewById(R.id.numberTwo);
        add = findViewById(R.id.add);
        subtract = findViewById(R.id.subtract);
        multiply = findViewById(R.id.multiply);
        resultView = findViewById(R.id.result);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String firstNumberString = numberOne.getText().toString();
                String secondNumberString = numberOne.getText().toString();

                int firstNumber = getIntFromString(firstNumberString);
                int secondNumber = getIntFromString(secondNumberString);

                int result = addTwoNumbers(firstNumber,secondNumber);

                resultView.setText(getStringFromInt(result));

            }
        });

        subtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String firstNumberString = numberOne.getText().toString();
                String secondNumberString = numberOne.getText().toString();

                int firstNumber = getIntFromString(firstNumberString);
                int secondNumber = getIntFromString(secondNumberString);

                int result = subtractTwoNumbers(firstNumber, secondNumber);

                resultView.setText(getStringFromInt(result));

            }
        });

        multiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String firstNumberString = numberOne.getText().toString();
                String secondNumberString = numberOne.getText().toString();

                int firstNumber = getIntFromString(firstNumberString);
                int secondNumber = getIntFromString(secondNumberString);

                int result = multiplyTwoNumbers(firstNumber, secondNumber);

                resultView.setText(getStringFromInt(result));
            }
        });
    }

    int addTwoNumbers(int a, int b){
        return a+b;
    }

    int subtractTwoNumbers(int a, int b){
        int tempMax, tempMin = 0;
        tempMax = Math.max(a, b);
        tempMin = Math.min(a,b);
        return tempMax - tempMin;
    }

    int multiplyTwoNumbers(int a, int b){
        return a*b;
    }

    String getStringFromInt(int value){
        return String.valueOf(value);
    }

    int getIntFromString(String string){
        return Integer.parseInt(string);
    }
}

Conclusion

  • We now know what is function, how to make them and why its return type is so important.
  • We know how to create view objects and initialize them
  • We know making functional blocks will enable the code to be reused anywhere.
  • We now know that we should be concerned about using Integer, Float or String while doing Mathematical processes as from EditText we will always get String.

Challenge for students

Try checking if the user input is empty or not inside each onClickListener for button. Checking them and stopping the function to run is very essential part of the process as the app will crash if there is no input but you are pressing the buttons. So remember to check if EditText has empty value or not.

GoodLuck~