How to build a simple Calculator app in Android Studio – Full Code and Explanation

What will you learn?

  1. Using OnCLickListener to interact with buttons.

Note: Find the full code of the project in the end of the post. Read the entire post for further clarifications and explanations.


Building the interface

As with all applications, we should always start with building the interface. For the calculator app, we require the following elements.

  1. TextView
  2. Buttons

That’s it. We use the textView to show users the numbers they have written and also to display the result of the calculations we are going to do.

Each of the numbers will have a different button, from 0-9 and we will have four additional buttons for addition, subtraction, multiplication and division. Other than this, we require a button to calculate the operation, a button for decimals, and a button to clear the display.

Requirements

1. EditText: To display numbers and the result.
2. Button: Numbers 0-9
3. Button: Operational buttons (+, -, *, /, =)
4. Button: Decimal button
5. Button: Clear display button.

Here’s a screenshot of what the code at the bottom would look like, if you were to paste it in your activity_main.xml file.

UI for our simple calculator app

Coding the Functionality of our simple calculator

Step 1: Creating objects for our elements

In your Java file, which is almost always MainActivity.java by default, head on over to the AppCombatActivity class, and inside that create objects for all of your 15+ buttons and an object for your EditText.

Button btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8, btn_9, btn_0, btn_Add, btn_Sub, btn_Mul, btn_Div, btn_calc, btn_dec, btn_clear;
EditText ed1;

Next, we will need two float values, to store the first number and second number.

float Value1, Value2;

And finally, we need four boolean variables to check what operation is going on.

boolean mAddition, mSubtract, mMultiplication, mDivision ;

Step 2: Fetching values from the elements into the working of our app

Inside the onCreate function, we will fetch all values and assign it to our objects. We do this by the following code

btn_0 = (Button) findViewById(R.id.btn_0);

Here, we are fetching the value of ‘btn_0’, which is the ID of our button zero, and storing it in the object ‘btn_0’ that we created earlier. Though, they are named the same, Android Studio has the ability to identify the correct one. But if it gets confusing for you, feel free to give either one of them any other names.
We do the same with our EditText.

ed1 = (EditText) findViewById(R.id.edText1);

Step 3: Changing the EditText value by pressing the buttons.

Here’s the code

btn_1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ed1.setText(ed1.getText()+"1");
    }
});

This is what happens when you push one. The editText, first already fetches the value that it is already displaying, null in this case, and then adds 1 to it. If we don’t fetch the existing value then it will become impossible to enter multiple digit numbers.

Do this on repeat mode for each of the numbers as well as the decimal. These are input buttons and the code is same for all.

Step 4: The functional buttons.

Here’s the code we are using for multiplication.

btn_Mul.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Value1 = Float.parseFloat(ed1.getText() + "");
        mMultiplication = true ;
        ed1.setText(null);
    }
});

We are using our first float value ‘Value1’ here. We use the simple function getText() to do that. Here since we pressed the multiplication button, we set it’s boolean equivalent variable to true. You will see how this is helpful in the ‘calculate’ button coding.

Now since after we press the multiplication button we have to input another number, we set EditText to display null value.

We do the same process for Addition, Subtraction, and Division. Only difference is that their respective boolean values will be set to True.

Step 5: Calculating, the actual functionality

Here’s the code of what happens when you or someone else presses the ‘=’ button after inputting another integer.

btn_calc.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Value2 = Float.parseFloat(ed1.getText() + "");
        
        if (mSubtract == true){
            ed1.setText(Value1 - Value2 +"");
            mSubtract=false;
        }
    }
});

A couple of things are happening here, firstly, we are fetching the value that you entered after pressing one of the 4 functional buttons (+, -, *, /) and storing it in float variable ‘Value2’.

Next we execute an if-condition to check whether our four boolean values are true and then run it’s subsequent code. In the above example, we are executing only the if condition for subtraction. For the full code, refer to the code below.

The main operation is happening in the ‘ed1.setText(Value1 – Value2 + “”);’ line. For other functions, replace the – sign with others.

Now write the code for all functions and run the app. If you do the first operation

2 + 2

You’ll get the right answer as

4

But there are still a lot of flaws in this app, and that’s why this is a basic version of the app, and not an advanced debugged version.

Flaws of this app that are not covered in this post

  1. We are only using 2 float values. So 2 + 2 will be 4. But if you do 2 + 3 + 4 you will get 7. It will store only the last two input values.
  2. The app crashes when we press any one of the functional buttons. This may require either and if-condition statement or a try-exception. Something that we will learn later on in an advanced calculator post

 

Checkout some more of our tutorials on Android.

1 Use Intent to start a new activity

2 Play Audio File using MediaPlayer

3 Weight Conversion app

4 Study about different Layouts in Android and which one to use when.

Full Code for the User Interface for Calculator App

Full Code for the Functionality of Calculator App

Remember to change your package name to what you are using!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.