How To Build Simple Counter Android App

In my first android app development post, I showed how you could easily create a simple to do list application from scratch. In this post however, we are going deeper or one step further by creating a Counter App that will change a value as well as the background color depending on which button is clicked. If you asking yourself of a use case, I am thinking of a scenario where you are playing family games and you want to keep score count. You can reset to zero when you are starting over. Pretty fun right? Let us look at the final product before writing some code:

Unlike my first post, this will not show you how to setup the development environment for android applications. If you need to do so, please read through the setup guide here and then come back for another exciting learning experience.

Counter App Definition

This app is relatively simple but not as simple as the todolist we created earlier. We will be using a few more things that might be new to you. Here are some of the things we will use in our development.

Instead of hard-coding strings, we will use values and resources that we will set inside the strings.xml file which resides in the values folder.

The main activity that we will define will implement an interface. In our previous tutorial, we used the OnKeyListener inside a method. We are not going to do that here because we want to make things easier to understand and stick to good coding styles.

There will be three buttons. Each of which will be listening for clicks. If one is clicked, we do something after knowing which one was clicked. The first button will add 1 to the counter, the second will subtract 1 and the third one will reset everything to 0.

There will be a few fancy things we will add: every time you click the reset button, the score background will change color. Likewise, when you click add or subtract, the score background will change as well. Styles, anyone?

The layout will include three components: TextView, EditText and Button. That is all.

I know you are probably thinking, show me the code. It is okay, but I think it is also good to understand the structure of the app before doing anything else.

Files that we will use

MainActivity.java

main.xml

strings.xml

Note: There are several folders that get created when you create a project using the Android tools on Eclipse. In those folders are files that you can use to add resources.Some, you don’t need to touch like R.java which is automatically generated for you. There is also the AndroidManifest.xml which we will talk about in the future tutorials. You are free to look inside those files but since we are not dealing with them directly in this post, I am not going to talk much about them.

Create Counter App project

Like we did in my first example, from within Eclipse IDE, let us go to File -> New ->Android Application Project. Fill in the details of your project and application. When you are done, you should have your project ready to go.

The easiest way to define the layout of your application is using the main.xml file that opens when your project is created. Yours might have a different name. While that file is open, you will see a Graphical Layout tab on the bottom of that file. To its right, you will see main.xml or whatever you named it. Here is a snapshot if you don’t mind:

As you can see, instead of typing all the xml inside main.xml file, you can simply drag and drop whatever components you want your app to show; like input areas, buttons, forms and many more. Doing that will save you a lot of time. Since we already have a TextView showing “Hello World”, we don’t need to drag a new one, we will instead edit the value and the name as well inside strings.xml file.

Drag and drop EditText – resize it as it pleases.

Drag and drop your first button.

Drag and drop your second button.

Drag and finally drop your third button.

Remember, what you see after dragging and dropping the components to your view is how your final app will look like. If you look inside your main.xml file, you will notice that EditText and three Buttons have been added and even positioned for you. Cool huh?

Using strings.xml file

I mentioned earlier that it is good to avoid hard-coding values in your app. Maybe your app needs to show different values for different countries or languages and that is why we use the res/values/strings.xml file. The Resource window looks like this:

We need to create four string names and values: Click Add, select string and add these:

name = intro, value = Score

name = addone, value = +1

name = subtractone, value = -1

name = reset, value = RESET SCORE

Type them without quotes. I am saying this because some people might have the idea of a string having double quotes around them. After creating these strings, we can now use them in our main.xml file:

main.xml

[xml]

[/xml]

First, we have our TextView where we use an id ‘myTextTitle’. As you can see, the last android:text has a value “@string/intro” – we just created that inside string.xml remember? The same applies to the three remaining buttons.

Note: Remember to Capitalize EditText, TextView and Button in your code – this syntax highlighter doesn’t do it as I would like it to. If you know a better highlighter for WordPress, please tell me.

We will need those ids to reference the components inside the java code that we will write next.

While defining our MainActivity.java class, we tell it to implement the OnClickListener interface which means we will have to use the onClick method . Eclipse is really cool, you only need to hover over MainActivity and double click it and a method is created for you. Repeat this procedure to import the necessary packages.

Immediately after that, we define our objects. EditText, Button, TextView and a counter variable which we set to zero. At this point, we just define them and leave them for later use.

From within onCreate method, we finally assign values to our TextView, Buttons and EditText references. We are using the ids we assigned inside main.xml for each one of them. You can always switch between the java code and the xml file to make sure you don’t make errors or name mismatches.

We then set the OnClickListener on our buttons passing in the (this) keyword – the context. Remember we are doing all these inside MainActivity class.

I realized the Score text was too small and I therefore increased the size to 24. Pretty straight-forward I think.

Finally, we define what we want to do every time a particular button is clicked. Using *if* statements, we see if View v is equals to button 1, 2 or 3. Once that is clear, we either increment, decrease or reset the counter. Again, I added some cheap styles – changing background colors depending on which button was clicked.

That, is all you needed for this application to work.

If you have any questions, please let me know. I will truly appreciate you sharing this post with your friends online. Have comments? I would love to hear from you. Thank you for learning with me.

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

Normally the debugger will show in red where the error message is and if you click that location, it opens up the code location where it is crashing. I don’t know exactly what could be causing your issue because you didn’t give more details on the error.

Please try making sure that all the syntax is correct, restart the Emulator if you use one or tablet or phone. In fact, I would uninstall it; Remember to always add each new activity to the Androidmanifest file each time or your code won’t work.

hello, I just read your post about:
how-to-build-simple-counter-android-app/
I need to count how many times the user clicks on a especific button in 24 hours, and then reset the counter. The user not always be in the app, So I figure i need to use a small data base to recover the counter every day.
What should I do?
thanks in advance…

[…] How To Build Simple Counter Android App – Android app development using a real Counter app will show you step by step how to create your first android app from start to finish. Java and Eclipse… […]

Nice article. Took 2 hours [I am an android beginner and new to java], but I was able to successfully debug it in Android Studio 1.3 with Lollipop. Ran it in Froyo attached device. Please share more articles.
~ Tariq Rahiman

Thanks for the counter code. I created a app that is used as a test simulator and I needed something to count correct answers as users navigated their way through all the questions. This was very helpful. I appreciate you, many thanks!

Is it possible to add more buttons that would also add values? Staying with increment by 1 each time.
I have 5 children and would like a button for each of us. I would also think it should be rather easy to display each persons points separately, however I am not sure of that.

Elisha, I very much enjoyed reading and following your tutorial. Thank you for such a quick response. Do you think it would it be possible for you to provide me sample code for the following requests?

1. How can I find the # of button clicks per button and perhaps display on the bottom of this Activity or perhaps have it switch Activity to display.
2. How to code in a Submit or Finish button?
I am a newbie having been at this now for 7 days and with lessons such as yours, I can actually measure a small amount of progress.