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:

simple android application

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

  1. MainActivity.java
  2. main.xml
  3. 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.

android applications project structure

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:

graphical layout android tools

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:

using android string xml file

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.

MainActivity.java

[java]
package com.simpledev.counterapp;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;

public class MainActivity extends Activity implements OnClickListener {

Button btn1;
Button btn2;
Button btn3;
TextView textTitle;
EditText scoreText;
int counter = 0;

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

btn1 = (Button)findViewById(R.id.addButton);
btn2 = (Button)findViewById(R.id.subtractButton);
btn3 = (Button)findViewById(R.id.resetButton);
scoreText = (EditText)findViewById(R.id.editText);
textTitle = (TextView)findViewById(R.id.myTextTitle);

//—set on click listeners on the buttons—–
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

// change font size of the text
textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
}

@Override
public void onClick(View v) {
if (v == btn1){
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.CYAN);
}
if (v == btn2){
counter–;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}

if (v == btn3){
counter = 0;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
}

}

[/java]

Code Breakdown

  • 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.

Be The First To Get New Posts From Simple Developer…

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

28 Comments on “How To Build Simple Counter Android App

  1. Moose Reply

    July 29, 2013 at 4:43

    The app crashes right after it is run.
    Thoughts?

    • Elisha Chirchir Reply

      July 29, 2013 at 4:57

      There are several possibilities here:
      1) There are errors in your code somewhere
      i)That could be inside the xml files or in the java code.

      Please tell me which file you had a problem with if you can.
      Remember that inside main.xml file, elements start with uppercase like

      • Moose Reply

        July 30, 2013 at 3:12

        I don’t really know what happened, but i re-did the whole thing and it worked this time.
        Thanks for the tutorial!

        For the code, try SyntaxHighlighter Evolved.
        Cheers!

  2. Nike Reply

    August 1, 2013 at 6:03

    Helpful tutorial !

    • Elisha Chirchir Reply

      August 1, 2013 at 6:21

      I am glad you found it helpful. Thank you for stopping by!

  3. Mark Reply

    November 24, 2013 at 2:50

    Please send me updates and newsletters from your site. Thanks in advance,

    • Elisha Chirchir Reply

      November 24, 2013 at 2:55

      All you need to receive updates is to subscribe through the form on the SUBSCRIBE page. Thanks for visiting.

  4. aleem ahmed Reply

    February 24, 2014 at 11:34

    I am having an error saying function main is not defined, searched all over the web couldn’t fix it. please help.

    • Elisha Chirchir Reply

      February 24, 2014 at 3:00

      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.

      Let me know if you need more help beyond this point.

  5. […] How To Build Simple Counter Android App […]

  6. Absolutkarlos Reply

    August 5, 2014 at 4:52

    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…

  7. Chance Reply

    October 7, 2014 at 6:21

    Mine wont to run. it only adds once and then stops how do i make it continue to add for every click.

  8. Waseem Akram Reply

    March 25, 2015 at 12:21

    i want to the code that if i click on button a counter is add into some activity and show the detail of the counter

  9. […] 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… […]

  10. tariq rahiman Reply

    August 26, 2015 at 4:25

    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

  11. Rico DeMarco Reply

    December 23, 2015 at 5:48

    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!

  12. Nigel Reply

    February 8, 2016 at 9:54

    Thank you, good source, It would of taken my ages to work out the Integer.toString. I was able to adapt the code to produce a Toast if the value was already 0.

  13. Gerry Reply

    February 13, 2016 at 8:58

    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 Chirchir Reply

      February 13, 2016 at 9:19

      You can add as many buttons as you need without a problem. Just repeat the same process.

      • Gerry E Reply

        February 13, 2016 at 1:48

        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.

        • Elisha Chirchir Reply

          February 13, 2016 at 3:37

          Gerry, I think I might find time to help you with this; but instead of doing it through the comments on my site, we can continue here on gmail?

        • Elisha Chirchir Reply

          February 13, 2016 at 6:19

          I have created a quick project to show what you might want Gerry; Here it is https://github.com/echirchir/gerry_demo Let me know if you need anything else.

  14. praveen Reply

    March 10, 2016 at 10:18

    good tutorial, working

  15. […] How To Build Simple Counter Android App […]

  16. mohsen Reply

    March 28, 2016 at 12:50

    thanks for your tutorial, as beginner am happy 2 see some errors but am straggling with one errors
    in main.java, it said view cannot be resolved to type (public void onClick(View v) {)
    any idea?

  17. Toni Reply

    April 24, 2016 at 9:43

    For me it doesn’t work, i can’t even get it to render it, i don’t know what is going on but it looks like a mess, probably there are a ton of things i did wrong but this is my main.xml http://prntscr.com/aw5ddn
    this are my strings http://prntscr.com/aw5dqw
    and this is MainActivity.java http://prntscr.com/aw5dzw
    if anyone knows how to fix this

  18. rijwan khan Reply

    May 6, 2016 at 10:52

    how to create a button which changes color on click but revert it’s action and change again to default on second click

Leave a Reply

Your email address will not be published. Required fields are marked *