Guide to Creating a Calculator in Android

Written by:  • Edited by: Simon Hill
Updated May 3, 2011
• Related Guides: Android | Google | Java

In this article we will finish creating our Android Calculator.

Placing the XML

In the First part of this article series we created, in XML, the User Interface. Now its time to get started with the Google Android code.

First of all, we need to create a new Android Project. We need to have configured Eclipse in the right way, as we saw in my first article.

In Eclipse:

File -> New -> (If “Android Project” doesn't appear here, click on the “Other...” option, and select "Android project").

The Android application structure will be created. We can see the src folder (source code), the res folder (resources) and the AndroidManifest.xml file (Configuration file). We will focus on the source and some resources.

Remember the .xml file we got in the last article when we created the Calculator UI? Its time to place it somewhere. Where? In the resources folder, we are going to put it in the main.xml file inside layout folder. So, copy the xml information created in DroidDraw and overwrite whatevers already inside the main.xml file.

In the layouts folder we are going to put the User Interfaces we are going to use in our applications. Ours, so we just need a .xml file.

Now, if you go to the R.java file inside src folder, you will see that new variables have been created, variables with familiar names!!! These names were the names we used in the User Interface (plusbutton, minusbutton). Java code use this R.java file to access the resources of the application.

In this R.java file, we can see different classes:

id class, stores all widgets Identifiers.

layout class, stores all variables that refers to layouts we have in the resources

string class, stores the variables of the strings we have in the resources

When we start thinking more about the Calculator, we realize that the inputs widgets must be numeric inputs. We can control this in java code, but, why not do it in the XML using some type of parameter?

For that, we have the “android:numeric” parameter. If we put this to a widget, in the .xml file, we are just saying to the system that that input widget is going to admit only numeric characters. Let's put the next parameter inside the inputs widgets:

android:numeric= “decimal|signed”

We are limiting the input values to decimals and signed.

So the code would look like this:

<EditText android:id="@+id/input2" android:layout_width="156px"

android:layout_height="wrap_content" android:textSize="18sp"

android:numeric= “decimal|signed”

android:layout_x="10px" android:layout_y="109px">

</EditText>

Source Code

Now its time go to the source code.

When we created the project, we put a name to the Activity, I used “Calculator”, so this is the main file of the Application.

Here, we can find the onCreate method. This is the method that its called when we create the Activity, so here we will initialize all variables.

First, we are going to create the widgets in the Java Code, using the following line-format:

input1 = (EditText) findViewById(R.id.input1);

Where input1 is a EditText type variable, and with the findViewById(R.id.input1) we associate this variable to the widget we create in the XML code (main.xml).

We create one variable for each widget: input1, input2, solution, operator and all buttons.

For buttons, we are going to assign a onClick event to each one. In this way, we will control when this buttons are clicked.

plusButton.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

//TODO

}

});

We create a OnClickListener, this element “listen” clicks events on this button (plusbutton) and when a click happens, the “onClick” method is executed.

Inside the onClick method we are going to put just a simple line:

operator.setText("+");

This is: “To the widget 'operator' (the one between the two Edits texts), assign the text '+'”. In the screen, when the "+" button is clicked, a "+" simbol will apear between the two EditTexts. I do this just to show how we can change the elements of the screen with the code.

The others buttons are the same, just change witch button calls the OnClick and the value inside the operator.setText().

The whole source code is here:

http://code.google.com/p/android-projects/source/browse/Calculator/src/com/bright/hub/Calculator/Calculator.java

When we arrive to the “equalbutton” we are going to do something different.

We are going to create some filter and show a Alarm when, for example, the inputs are empty and we press the “=” button.

Creating the Alarm is so simple:

show = new AlertDialog.Builder(mContext)

.setTitle("Error")

.setMessage("Some inputs are empty")

.setPositiveButton("OK", null).show();

Where mContext is the actual Activity, “Error” is the title of the Alert and “Some inputs are empty” is the message. We can add a button with the “Ok” message. And all this is shown, using .show(); method.

Now, we are going to check the value of the “operator”, when we click on the “equal button”, depending on what its on it (“+”,”-”...) we do an operation or other and we put the value on the solution EditText.

if (operator.getText().equals("+")) {

double result = new Double(input1.getText().toString())+ new Double(input2.getText().toString());

solution.setText(Double.toString(result));

The full source code is in my new created Google Code acount:

http://code.google.com/p/android-projects/source/browse/

This is a very simple example, just for learning. In further examples we will complicate the code.

Follow up

If you want to know when new articles are released, subscribe yourself to the Google Android RSS Otherwise, you can follow my research, articles and work in my professional twitter: jbeerdev


Comments

Showing all 8 comments
 
davey Apr 8, 2011 11:19 AM
RE: Guide to Creating a Calculator in Android
hi im a newb when it comes to java programming. what programming language is used for the java here is it c, c++ or c#?

thnx
Saranya.R Jun 10, 2010 1:59 AM
Adding more than 2 numbers
Ur implementation for calculator is very useful.But can u tel me how to make it to add more tham 2 numbers?
Jbeerdev Mar 28, 2010 1:38 PM
RE: Guide to Creating a Calculator in Android
Hi manoj

So, you want to show images in a dynamic way. There is something you can do:

You can store the images in a SD card folder, then, from code, and using the text you have entered in the eddittext, you can search if the image name exists in that folder (Using the "File" class) and if it exists, show it in the screen, using an imageview.

Here, in this tutorial, there is some useful information you could use:

http://www.brighthub.com/mobile/google-android/articles/64048.aspx
Jbeerdev Mar 28, 2010 1:33 PM
RE: Guide to Creating a Calculator in Android
Hi Muhammad and m3g4hur7z.

I will be pleased to write and explain the code its missing. Please, If you could provide me the most important points you think I should go deep in code, this will help.
manoj Mar 23, 2010 12:27 PM
need help
hey i am following u r tutorial.its usefull for me. now i just want to know how to link a image (i.e if i write "home" in edittext box and press the button then it has to display that image "home" stored in our folder. simarly for other images also.). so i need to know how to write the java code for this...if u know please help me...
m3g4hur7z Mar 19, 2010 7:28 PM
Enhance tutorial
He's right, I have no idea how to understand all of this being such a beginner. I don't understand where to input the Operator ID in Main.xml so R.java has reference for the Calculator.java

Eventually I'm sure I'll figure it out but to finish this tutorial you should make a PART 3 explaining all the sections of code you missed. Would be a big help, thanks!
Muhammad Jan 16, 2010 5:51 AM
upgrade calculator
your implementation of calculator doesn't show how to focus EditViews
Muhammad Jan 16, 2010 5:49 AM
upgrade calcuator
your implementation for calculator is good but u haven't
shown how to set focus to different EditViews
 
blog comments powered by Disqus
Email to a friend