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:

android application beginner 300x300 How To Build Simple Counter Android App

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 resource files 300x252 How To Build Simple Counter Android App

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 300x231 How To Build Simple Counter Android App

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:

string xml android file 300x231 How To Build Simple Counter Android App

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

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <textview android:id="@+id/myTextTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText"
        android:layout_alignLeft="@+id/addButton"
        android:layout_alignTop="@+id/editText"
        android:layout_toLeftOf="@+id/editText"
        android:text="@string/intro"></textview>

    <edittext android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:ems="10" >

        <requestfocus></requestfocus>
    </edittext>

    <button android:id="@+id/subtractButton"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_above="@+id/resetButton"
        android:layout_alignLeft="@+id/addButton"
        android:layout_alignRight="@+id/addButton"
        android:text="@string/subtractone"></button>

    <button android:id="@+id/addButton"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_above="@+id/subtractButton"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/editText"
        android:text="@string/addone"></button>

    <button android:id="@+id/resetButton"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_alignLeft="@+id/subtractButton"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/subtractButton"
        android:layout_marginBottom="102dp"
        android:text="@string/reset"></button>

</relativelayout>

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

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);
		}
	}

}

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.

12 thoughts on “How To Build Simple Counter Android App

    • 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 I apologize for the mistakes made by this syntax highlighter.

      If you still get errors after that, you can talk to him via Google+ or Twitter @Eenvincible

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

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

  1. Pingback: How To Build Simple Counter Android App - appgong

  2. 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…

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">