DAY 13: Adding Increment & Decrement Methods To My App

Getting familiar with increment and decrement methods in Java to add new functionalities to my brand-new app




For the last two days I have been again involved in practical exercises in Android app development and I feel now it’s time to write about what I have learned. Even though I have some slight experience in programming, I am going to describe here absolutely every thing I learn about and practice. Not only is it a great practice for me but also a great source of free knowledge for you.

As you can see I don’t always manage to both learn and create a post (on the same day). That is because by end of April I will still have some extra duties but this is going to drastically change after I come back from my short trip on the 3rd of May. After that date you can expect one post (in the form of a day) almost every single day.

A Few Words About My App & What It Does

Based on the knowledge I gained from the Udacity course, I  created a very simple app in which I used the increment and decrement methods used in Java. This is how my app looks like.

Increment and decrement methods in Java

As you can judge from its interface, my app lets me calculate my value as an Android developer on the market.

Using the + and buttons I can either increase or decrease my experience (let’s say that my experience is here expressed in points). I set one point of experience to be worth $9.

The more experience points I add, the higher my value on the market. To calculate my value on the market I just have to hit CALCULATE and the worth will be displayed on the screen.

To make this app work and look like how it looks like, I had to modify two files: activity_main.xml (where I customized how the app and its views look) and  MainActivity.java (how the app’s “engine” works, i.e. calculates the value). 

Contents of  activity_main.xml

Below you can see the whole code for file activity_main.xml. It’s a bit longish and I am almost  sure that it’s far from being perfect (because the app doesn’t look the best in the landscape mode 😛 ) but in this example I just wanted the app to look decent and focused on what it does, that is, calculates the value of Android programming experience on the market.

This is my code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#616161"
    tools:context="com.example.android.experience.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="My experience as an Android developer"
        android:textAlignment="center"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="#8C9EFF"
        android:textAllCaps="true"
        />
    <Button
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:layout_marginLeft="130dp"
        android:layout_marginRight="130dp"
        android:text="+"
        android:textSize="50dp"
        android:textColor="#90CAF9"
        android:onClick="increment"
        android:background="#76FF03"
        />
    <TextView
        android:id="@+id/quantity_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_marginRight="160dp"
        android:text="0"
        android:textSize="46sp"
        android:textColor="#90CAF9"/>
    <Button
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:layout_marginLeft="130dp"
        android:layout_marginRight="130dp"
        android:text="-"
        android:textSize="56sp"
        android:textColor="#90CAF9"
        android:onClick="decrement"
        android:background="#76FF03"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Value on the market"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="#8C9EFF"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginTop="16dp"
        />
    <TextView
        android:id="@+id/price_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="0$"
        android:layout_marginLeft="120dp"
        android:textSize="36sp"
        android:textColor="#90CAF9"
        android:layout_marginTop="16dp"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:layout_marginTop="16dp"
        android:text="CALCULATE"
        android:onClick="calculateExperience"
        android:textSize="30dp"
        android:layout_marginLeft="89dp"
        android:background="#3D5AFE"
        />
</LinearLayout>

To put the above code in plain English, here are some of the elements and attributes I used to make my app look the way it looks:

  • LinearLayout to position the views one below another one.
  • I set the orientation of the ViewGroup to be vertical.
  • I used four TextViews which display the following text: My experience as an Android developer, 0, 0$ and Value on the market
  • I used two Buttons (with the + and – signs) which are used to increase and decrease the amount of my experience.
  • I styled my views by changing font sizes, font styles, background colors and so on.
  • In some places I set margin and padding values so that, for example, buttons are displayed in the center. I know I didn’t do it correctly because the app looks horrible in the landscape mode (but I am going to fix it soon).

That is basically all regarding the looks of my app. Let’s now get to its engine, i.e. file MainActivity.java.

Adding Increment & Decrement Methods In Java

All of the code in the activity_mail.xml is responsible for how the app and its specific elements (Text Views, Buttons, Image Views and so on) look on the device.

However, if we want the app to be a bit smarter and perform certain operations we need to refresh our knowledge about Java. That’s because Android is basically Java and the only way to make apps work is to apply the rules of Java.

Pseudo code for my app

One of the most important habits of every developer should be to at first write pseudocode (click to learn more about what it is) for the app and then turn it into real and working code. Pseudocode is simply a set of descriptive instructions of what the app is supposed to do (so that we, developers, better understand what we want and how we will code it).

In the case of my app it will look something like that:

  1. When I open the app it displays the initial value of 0 for both my experience as an Android developer and my value on the market.
  2. When I hit the plus button once it increases my experience by one. If I hit it twice, it increases my experience by two.
  3. If I hit the minus button once, it decreases my experience by one. If I hit it twice, it decreases it by two and so on.
  4. When I click the CALCULATE button, the app will calculate my experience and display it under value on the market.
  5. The value is calculated assuming that one point of experience is worth 9$.

Here is the content of my MainActivity.java file and below you will find its detailed explanation.

package com.example.android.experience;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;

import com.example.android.experience.R;

import java.text.NumberFormat;

/**
 * This app calculates the value of experience in Android programming on the market
 */
public class MainActivity extends ActionBarActivity {

    int quantity = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * This method is called when the calculate button is clicked.
     */
    public void calculateExperience(View view) {
        display(quantity);
        displayValue(quantity*9);
    }
    /**
     * Increment
     */
    public void increment(View view) {
        quantity = quantity + 1;
        display(quantity);

    }
    /** Decrement
     *
     */
    public void decrement(View view) {
        quantity = quantity - 1;
        display(quantity);
    }
    /**
     * This method displays the amount of experience on the screen.
     */
    private void display(int number) {
        TextView experienceTextView = (TextView) findViewById(
                R.id.experience_text_view);
        experienceTextView.setText("" + number);
    }

    /**
     * This method displays the given value on the screen.
     */
    private void displayValue(int number) {
        TextView valueTextView = (TextView) findViewById(R.id.value_text_view);
        valueTextView.setText(NumberFormat.getCurrencyInstance().format(number));
    }
}

This isn’t 100% my code because I used some of it from what was already provided in the course and modified it a bit to that is suits the need of my app. Let’s delve a bit deeper into its specific features and methods used.

Set the initial quantity of experience to 0

On the first things to do is to set the initial value of experience (let’s call it quantity of experience) to 0 and set it as a global variable (so that it isn’t destroyed after the execution of the method and it can be called from any place in the code).

If we use a global variable for it, the app will remember its value and increment and decrement it each time we hit the + or – button. If we don’t use a global value, the + and – button will only increase or decrease our experience by one no matter how many times we hit the + or – button.

    int quantity = 0;

This is basically all we need to write to set the initial value of experience to 0. It’s important to place this line of code at the beginning of file just after

public class MainActivity extends ActionBarActivity {

If we do it like this, then this will be a global variable (its scope will be global instead of local) which can be called from any part of the app. Once we declare the variable, we can move on to adding the increment and decrement methods.

Adding the increment method in Java

All you need to do to add the increment method is add such lines of code to your MainActivity.java file:

   public void increment(View view) {
        quantity = quantity + 1;
        display(quantity);

    }

As you can see, I didn’t declare the variable in this method (if I had, this would have been a local variable that would only work within the scope of this method) but instead I called it so that every time the CALCULATE button is clicked 1 will be added to the stored value of experience (quantity of experience) and the updated value will be displayed.

Adding the decrement method in Java

As you probably guessed by now, adding the decrement method is analogical to how we added the increment method. We just need to place the following lines of code.

    public void decrement(View view) {
        quantity = quantity - 1;
        display(quantity);
    }

By adding -1 we ensure that the currently stored value of quantity (amount of experience) will be decreased by one once we hit the minus button. We didn’t declare a variable within this method but, like above, called the global variable we declared at the beginning.

Using the global variable scope means that all the methods within the MainActivity can refer to this variable and update it. In this specific case, it means that both the increment and decrement methods can refer to and update the quantity variable (amount of my experience as an Android developer).

How the CALCULATE button does its job

The above two methods let you increase and decrease the amount of experience as an Android developer. However, the whole point of the app is to calculate how much value a given amount of experience has on the market.

To do that, the app needs to make a calculation using the values you provide (i.e. the amount of experience). Here is the code for the CALCULATE button:

   public void calculateExperience(View view) {
        display(quantity);
        displayValue(quantity*9);
    }

As you can see the name of this method is calculateExperience and all it does is display the calculated value of my experience on the market by following a simple formula: the amount of experience multiplied by 9 (I assumed that one point of my experience it worth $9).

This method is called from the CALCULATE button by adding the line of android:onClick=”calculateExperience” in the xml code for the Button.

  <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:layout_marginTop="16dp"
        android:text="CALCULATE"
        android:onClick="calculateExperience"
        android:textSize="30dp"
        android:layout_marginLeft="89dp"
        android:background="#3D5AFE"
        />

I planned this to be a short and to-the-point post and I see it’s almost 1800 words. I really felt the flow! That’s enough for now. What I am going to do now is proceed with the course and practical exercises (as soon as I walk my dog).

If you have any questions or comment, feel more than welcome to use the comment box below! 🙂

Add Comment