A Simple Calculator [Android]

We are going to see how to create a simple calculator for Android platform. This is like a hello-world program and is really easy to do.

Please Leave A Reply To Improve The Content

Tools we need / that I used :
  • Eclipse with All android plug-ins installed ( How to install? Ans:  Here ).
  • Android SDK with at least one platform installed (I use Android 4.0.4).
Prior knowledge required :
  • Well, you need to how Mark-Up language works. At least you should know what is tag and its attributes. Best way to learn, learn HTML. We use XML that doesn't differ much from HTML except for the namespaces, you use android:[attribute]="" instead of [attribute]=""
  • A little java on handling the data types and simple castings.
  • How to run apps in android phone. Just click them on the icon :P.
  • How to recommend this tutorial to others : Click the  +1  button at the end

STEP I : Starting Your Project

Start Eclipse and create a new project (File -> New -> Project...). In the Dialog select Android from the tree and in the sub-category select Android Project. 

Press Next to enter your project name (I use Simple Calculator) and Next:
  • If you are first time configuring, the dialog will ask for the location of android_sdk folder.
  • Else or after the above point, it will ask for the platform to your applications, the platforms you have installed in your SDK.
In the last Dialog, the only thing you need to do is set up your package name. You can give any name; apps.myfirstapp, com.calculator, apps.simple.calculator . . . anything. But be sure you have the format ___.___. (I use apps.simplecalculator)

STEP II : Getting the Interface Done

We have two types of files to deal with
  • A .xml file, located in your project-tree -> res -> layout -> main.xml that concerns the user interface.
  • A .java file, located in  your project-tree -> src -> apps.simplecalculator -> SimpleCalculatorActivity.java which contains the code behind.
Keep these two files open.

In the main.xml file we have two views; xml view and graphical view.

First lets deal with the graphical view. We need,
  • 3 TextViews (labels) : Text - Number 1, Text - Number 2, Text - that holds the result.
  • 2 EditTexts (text boxes) : Getting number 1 and number 2.
  • 4 RadioButtons : Choosing the operation; +, -, *, /
  • 1 Button : To perform the calculation
Drag and drop them on the canvas in graphical view and arrange them in the order as shown. ( Forget about the RadioGroup. We will add it later. )

 So the Layout looks like this.
Now go to the xml view and we need edit these in the tags.

If you are at the basics, then:

=> For every view (the components are called view), we need sat three attributes in minimum: 
  • android:id - android:id="@+id/<component id>"
  • android:layout_height - android:layout_height="wrap_content"
  • android:layout_width - android:layout_width="wrap_content" (For other layouts see android documentation)
If you can understand the tags, then its easier. We should have the above mentioned attributes for each tag.
Customize the ID attributes to recognize them easily. Remember the syntax is android:id="@+id/<component id>". NOT android:id="<component id>".

You can refer mine so that you we are synchronized. (Once again we forget the RadioGroup)

We see the format  [icon] ID (COMPONENT TYPE) - "TEXT".
  • ID is the name we give to the component
  • (COMPONENT TYPE) is the type of the component, if you use default names like textView1, they will not show the type. See the last one txtResult? I changed the id and we get the (TYPE) thing.
  • "TEXT" is the text that is displayed on the screen.

STEP III : Grouping the Radios

Now to RadioGroup I was talking about. If you had noticed the RadioButtons rbAdd, rbSub and others are grouped into something called RadioGroup id-ed radioOperation. This is because, if you familiar with the working of radio buttons in HTML then you would know that the radio buttons are to be grouped under a single name if they are to work. Oh! They will work however, all the radio buttons can be checked, if not grouped, at same time and we are not performing all the operations at a time. If you want you can run the project and test the RadioButtons in your AVD.

So, we are grouping. Create a tag before the first RadioButton text-ed "
ADD" with following syntax.


And put a close tag after the fourth radio button.


Put an attribute to the ADD radio button for it to be checked by default.


Here is the complete main.xml file for reference. ( I don't appreciate the view in browser (except firefox and opera). So save it and view it in a understandable manner ).

If you check out the OutLine of you project now can see the above screen shot with the radio group.

STEP IV : The Charming Program

Now switch to the java file which we opened. Initially the java file would be like this

To do our job we need to import some packages, so add them to the importing column.

  • import android.view.View;
  • import android.view.View.*;
  • import android.widgets.*;
Now we need to get the instances of the xml components into our java program, for which we need declare some associations which will connect the variables in .java file and components in the .xml file. If you are familiar with javascript in HTML then this is similar to that; we need find the element by its ID.
Note: All the declarations and functions are to come under onCreate( ) function
In javascript we use :
          var txt = document.getElementById();

In java we use :
          final EditText txt = (EditText)findViewById(R.id.txtNum1);


  • EditText is the data type 
  • (EditText) is for casting the component into EditText type
  • findViewById( ) is function to get the component by its ID
  • and R.id contains the list of IDs we declared in the xml file. If you press '.' after the id the intelliSense will show the list of available IDs from the xml file.
We need declare the associations for 3 Inputs, 1 processing and 1 Output; num1, num2, operation, buttonClick and result. So,

If you had noticed, we didn't associate the radio buttons but the radio group. We will see later why we selected the group instead of individual buttons.

Now we need to create an OnClick event for the button btnCalc in which we perform the calculation. For the btnCalc  set an onClick listener as shown.

OnClickListener is an Interface and you need implement the methods it contains 
     i.e the onClick(View arg0)

And use setText( ) and getText( ) functions to interact with the components' display strings.

So, on click of the button perform following steps.

If the numbers are empty, display an error message. (I use Toast for that)

  • Parse the numbers from the txtNum1 and txtNum2 text boxes
  • Get the SelectedID from the RadioGroup to get the type of operation
  • Construct a If-Else ladder to perform the opertaions. (Compare the SelectedRadio's Text with Assigned Text for each radio button to know which Operation is selected, a simple way.)
  • In division operation check if not the number 2 is zero to avoid DivideByZeroException.
Well, whats now? Lets run it and see how is our handiwork . . .

Click to Zoom

Hope you had a nice hand on the Android
Bye Bye! See you with another dive!

So long,


Popular posts from this blog

How to show only month and year fields in android Date-picker?

How to construct a B+ tree with example

Homebrew uninstall