DAY 15: Using Strings In Android

Hello everyone on a beautiful Saturday morning (at least here where I live). For the last two days I have been (obviously) learning Android app development and I am going to share with you my newest knowledge about strings in Android in just a few seconds.

Unfortunately, I didn’t manage to create as many app development posts as I wanted because I focused on reviewing my newest phone Samsung Galaxy S7. I need to better balance app development posts with other “regular” posts with technology tips and tricks. Both types of posts are great fun for me to create and that’s the problem. 🙂

I am getting towards the end of course Android Development for Beginners and I am really happy with my progress (even though I wish I was making it more quickly).  Today I’ve finished learning about strings in Android and how to concatenate them. Let’s start!




What Are Strings In Android?

As I mentioned before, Android programming is basically Java so when I talk about “strings in Java” and “strings in Android” I mean basically the same thing.  Let’s now try to define what strings are so that the rest of this tutorial will make perfect sense both to you and me.

I reviewed the definition of strings at Android for All (a great resource you should use) and this is more of less what I found:

  • A string is a series of characters (like letters, punctuation marks, numbers or even blanks).
  • A string may consist of randomly chosen words or characters.
  • A string may contain variables in it.
  • The length of a string is the number of characters that are in the strings.
  • A string may contain no characters at all. In such a case it’s called the empty string.

It turns out that in practice we encounter strings all the time in almost any app we use. I didn’t realize that!

For example, the below app I created for the needs of the Udacity course calculates the price of coffee you want to order. This is how the app looks like before clicking the ORDER button and choosing and quantity of cups or coffee and what happens after you click it.

Strings in Android

What my app displays under PRICE is a string of characters and a number (which is in fact a variable). Let’s now dive into the practical part and see how I actually coded this string and made it work.

I still haven’t properly set up my account on GitHub (and I won’t do this until I finish this Android app development course), so in the couple of next app development posts I will be pasting all of my code in the post. 

If you want to reproduce my above app here is its code and below you will find my further comments.

Code for file activity_main.xml

<?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"
 tools:context="com.example.android.justjava.MainActivity">

 <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginBottom="16dp"
 android:text="Quantity"
 android:textAllCaps="true" />

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">

 <Button
 android:layout_width="48dp"
 android:layout_height="48dp"
 android:onClick="increment"
 android:text="+" />

 <TextView
 android:id="@+id/quantity_text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="8dp"
 android:layout_marginRight="8dp"
 android:text="0"
 android:textColor="#000000"
 android:textSize="16sp" />

 <Button
 android:layout_width="48dp"
 android:layout_height="48dp"
 android:onClick="decrement"
 android:text="-" />
 </LinearLayout>

 <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="16dp"
 android:text="Price"
 android:textAllCaps="true"
 android:textSize="16sp" />

 <TextView
 android:id="@+id/price_text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="16dp"
 android:text="0$"
 android:textColor="#000000"
 android:textSize="16sp" />

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="16dp"
 android:onClick="submitOrder"
 android:text="order" />
</LinearLayout>

Code for file MainActivity.java

package com.example.android.justjava;

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

/**
 * This app displays an order form to order coffee.
 */
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 order button is clicked.
     */
    public void submitOrder(View view) {
        int price = quantity + 5;
        String priceMessage = "Total $: " + price;
        priceMessage = priceMessage + "\nThank you!";
        displayMessage (priceMessage);
    }
/**
 * 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 given quantity value on the screen.
     */
    private void display(int number) {
        TextView quantityTextView = (TextView) findViewById(
                R.id.quantity_text_view);
        quantityTextView.setText("" + number);
    }

    /**
     * This method displays the given price on the screen.
     */
    private void displayPrice(int number) {
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
    }
    /**
     * This method displays the given text on the screen.
     */
    private void displayMessage(String message) {
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(message);
    }
}

Adding Strings In Android

Everything I am talking about today happens in the MainActivity.java file of my app but you definitely need to know the contents of activity_main.xml to be able to reference to this file. The first thing I had to do was to add a new method at the end of the MainActivity.java file so that the string of characters will be properly displayed.

  private void displayMessage(String message) {
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(message);
    }

I don’t really know what is happening in each of the above lines but I know that I need this method for my app to work and so do you. 🙂

What I am now interested in is modifying the submitOrder method and adding a string there. This is how I coded this method.

    public void submitOrder(View view) {
        int price = quantity + 5;
        String priceMessage = "Total $: " + price;
        priceMessage = priceMessage + "\nThank you!";
        displayMessage (priceMessage);
    }

In the above code we declared a new string variable named priceMessage and the value that is holds are the characters (Total $: ), the value of a variable (called price) and a sequence of characters (Thank you!) that start in a new line. Let’s draw the formula for declaring strings in Android.

Strings in Android

As you can see in the above formula at first we need to “announce” what type of data is coming. Next we need to give our string variable a name. It’s important to use a descriptive name which will indicate what this variable will store so that other people working with our code will know what we meant.

It’s important to remember that in Java variable names are case-sensitive and they usually start with a lowercase letter and use Camel Case if there are many words in the name (just like I did).

After the variable name we have the assignment operator, that is, the equal sign (=). This operator simply assigns the value to the variable we have just defined.

In this case we specified the initial value of the string variable to be the text in double quotes  (a string literal with a fixed value and a space). The value of the price variable that is defined with these lines:

 int price = quantity + 5;

Obviously, at the end of the statement there has to be a semicolon (without it our app won’t run).

How To Concatenate Strings In Android

If you know a little about programming, you probably noticed that in the above formula I have already concatenated (i.e. combined or joined) two strings with the plus (+) operator.

concatenate-strings-in-android

This is basically how you concatenate strings in Android (or simply in Java). Even though string concatenation is a very simple concept, there are a few rules to remember:

  • To join strings together you use (as mentioned above) the plus operator you know very well from math.
  • If you concatenate literal strings (those with a fixed value of, for example, a set of characters), you need to put them in quotation marks. Example: “Total $: “
  • To add space between literal strings, you need to add it within the literal. Example: “Total $: “ (There is a space after the semicolon)
  • If we want our string to go to the next line, we need to make use of escape characters. In the case of my app, we need to place \n before the set of characters that must go to the next line.
  • If we want to place integer values into our strings, we don’t use quotation marks for them. Example: “Tomorrow I will run ” + 42 +”kilometers” (That’s true :P)

That is basically all for today’s post and what I now know about strings in Android. You can learn more about strings in Java in its official documentation.

Summary Of Day 15

Day 15  of my Android development journey has come to an end and I feel extremely satisfied and happy.

What I want to say: I am also a bit stress because tomorrow I am running a marathon. 
Level of motivation: Extremely high
Level of fatigue: Low
Level of experience: 0.0049%
What I have learned: I am slowy getting towards the end of the first Android app development course and I know what strings in Android are and I know who to correctly use them.

Share Your Thoughts

Are you an Android developer? Did you notice any errors in this post? Do you have any questions or comments?

I am only beginning my journey of becoming an Android developer and I would really like to hear from you (and learn form you). Feel free to either contact me directly or leave me your comments in the comment box below.

Add Comment