Android Tutorial: Creating Your First Hello App

Josh Android Leave a Comment


Hi all, this is going to be part 1 of a series of an Android tutorial development! I’ve spent a good year working on Android and have learned a lot.

However, for the first part of the tutorial, we’ll get orientated with what Android provides by creating a simple Button app!

I will assume that you will have limited knowledge of Android so I will try to explain everything.

However I’m also assuming that you have some knowledge in java or other programming languages. If not I highly recommend going through Code Academy for Java

Setting up the project

If you don’t have Android Studio already installed, go here and install Android Studio

Have Android Studio installed? Good!

First thing to do is to create a new Project. Go to File -> New -> New Project…

1NewProject

You’ll see 2 fields,

  • application name – This is the name of our project. In our case I called the project HelloWorld
  • domain name – This is a unique identifier for your app if you decide to submit it to the play store. It can be anything and it can be changed to something else later.

Afterwards you’ll see a list of targeted API level:

1_1APILevel

Every phone has an API level based off of the current update they’re on. The newer updates have performances fixes and new features.

So why would you ever want to use older API’s you might ask? Depending on what phone you have, you can’t upgrade to the newer API levels.

As a result, if developers want to support more people, they’re going to have to develop at a lower level API.

I recommend using API 15 as your baseline. At the time of the writing API 15 (IceCreamSandwich) supports 94% of the whole Google Play Store.

Next you’ll need to select to add an activity to your project. Activities are your java files where you put your code in.2SelectLayout

For now just select an Empty Activity and you’ll see:

3ActivityCreation

You’ll see 2 fields on the next page:

  • Activity Name – the name of your activity, or your java file where you put your logic. We’re just calling it HelloActivity.
  • Layout Name – Every activity will have a layout associated with it. We’ll talk more about what layouts, are but they’re just the GUI (Graphic User Interface) to your app. The app will change it. Just leave it to be activity_hello

Now that you’re done you should have something like this:

4CreatedProject - Copy

Now if you click on the project bar on the left you’ll see a lot of folders that makes no sense to you at all.

5SelectProject

6ExplainProjectFolders - Copy

I’ll give a brief overview of what they’re for:

  • manifests – Holds your AndroidManifiest.xml which is where you add permissions that you need to run your app on your phone. For example: GPS, internet access, etc
  • java – Inside the java you’ll see your domain name that you selected. There are 2 of them, the one that says androidTest is there for you to write tests for your app and the other folder that contains your TodoActivity is where we put all of our files.
  • res
    • drawable – This is where you put all of your pictures
    • layout – Layouts contains the xml files that creates the GUI for each of your activitiy
    • mitmap – Similar to drawable except mitmap is where you put your icons
    • values – The files in here are used to make your life easier by setting constant values that you can call on later. It might seem like a pain in the butt, but if you ever decide to change anything in the future you don’t have to go throughout your codebase to change everything.
  • Gradle – We won’t talk much about gradle, but gradle is used to compile and run your code. There are many useful features like using 3rd party libraries, but we won’t get to it in this tutorial.

Now that we have everything up and running let’s understand our code:

package net.joshchang.josh.todolist;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class HelloActivity extends AppCompatActivity {

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

First the class header: you’ll notice that your class extends something called AppCombatActivity.

Without going to deep into the technical details, AppCombatActivity and other Activity classes are the what displays the content of your app.

For now just understand everything you use in Android extends on an already existing class and you’re just overriding their methods to create the features that you want to use.

A look into the Android Life Cycle

Inside our class we have an onCreate method that’s already provided for us.

The onCreate method is one of the methods in the Android LifeCycle which you can see here:

LifeCycle

I’ll talk more about the Life Cycle in the future, but just know that onCreate is the first method your Activity when you app opens up.

The first line of code we see is this:

super.onCreate(savedInstanceState);

This is us calling the onCreate function of our super class. Because of the complexity of Android we have to initialize our super class so that your app functions as it should. Generally speaking whenever you’re overriding a method in an activity or anywhere else you want call your super class to make sure your app runs properly.

The next line of code is initializing the GUI for your app:

setContentView(R.layout.activity_hello);

setContentView is a method of your class that you inherit. What it does is that it chooses one of your layout in your res folder to be the GUI for the activity.

Passing into the method, you’re giving <R.layout.activity_todo> R is a class that contains the path to the contents inside your res folder.

For simplicity sakes just think of R as res.

Every Activity class you create you’ll need to create an xml layout to display a UI to the user.

Note: Now I know it’s a pain to figure out what methods you inherit especially when Android is completely new to you. But as you continue to develop in Android you’ll come to recognize these methods. Of course you could always look through the Android Activity Documentation!

First Line of Android Code

So now that our long winded explanation of 4 lines of code is over, let’s actually start writing code. To create our simple HelloWorld app we’ll need 3 widgets:

  • TextView – To display our text
  • Button – To change what’s currently being displayed
  • EditText – To allow you to type in something new to display

Head over to app -> res -> activity_hello.xml:

7SelectLayoutFile

You’ll see something like this:

8real WhatXMLLooksLike

This is the design editor for your layout. With this, you can easily drag, drop, and edit your widgets without code. It’s really handy for getting something out quickly regardless of your experience.

On the right pane, you’ll see the Component Tree Pane. It allows you to see all the properties that your widget contains that you can change.

7PropertyPane

The more important properties are even highlighted for your convenience.

However if you already know what you want, it might be faster to go in and edit the properties of your widgets directly in your layout xml.

For my convenience we’ll be working with the xml source code, however you can just as easily drag the widgets in the Design Editor to get similar results

Click Text at the bottom at left corner of your activity_todo.xml window and you’ll go to the source code of your xml file:

8ClickText

Your code should look like this:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".TodoActivity" >
   <!-- Note that the padding above is actually using a shortcut, specifically
    @dimen/activity_vertical_margin and @dimen/activity_vertical_margin
    if you don't have these values, you can also hardcode 16dp
   -->

    <TextView android:text="Hello World!" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2" />

</RelativeLayout>

Looks confusing? Don’t worry, after you have made a couple of layouts you’ll realize that it’s not really as complicated as you might think.

In layout folders everything is represented inside a pair of <> and ends with another pair </> such as:

<Button> </Button> or you can even do this <Button /> to open and close the tag

Inside each of these tags you can add attributes inside them to change what your widget will look like.

Overtime you’ll learn more and more widgets and how to use them.

What we have here are:

  • Relative Layout – A container that’s used to hold widgets or other containers
  • TextView – A widget that allows you to display words

Lesson On Layouts: Relative Layout vs. Linear Layout

On a side note, if you have been seen other tutorials you’re bound to encounter Linear Layouts. What’s the difference?

Relative Layout allows you to position items anywhere in your container relative to where other widgets or the relative layout are located.

An example:

9RelativeLayout

Linear Layouts doesn’t have the feature. Linear layouts are more restricted in that your widgets are ordered linearly either horizontally or vertically where widgets won’t be stacked on each other.

An example of linear layout with the exact same widgets the only difference is that it’s using Linear Layout instead of Relative Layout:

10LinearLayout

Now for our first line of layout code!  We’re going to start adding our components inside our xml.

<?xml version="1.0" encoding="utf-8"?>
<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=".HelloActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="99dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="148dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

And you should have something that looks like this:

8WhatXMLLooksLike

So what do these properties mean? Well let’s go through them.

  • android:id – The ID of the widget. This has to be a unique name so you can refer to this specific object in your code.
  • android:layout_width and android:layout_height – These attributes describe the width and height of your widget. wrap_content wraps makes the widget as big as the text/size you set. match_parent makes your widget match the size of its container which can either be the layout or the size of your screen
  • android:layout_alignParentBottom, Top, Left, Right (Only used with Relative Layout) – Aligns the widget to the locations that you set inside the parent, which can be the layout or screen.
  • android:layout_toLeftOf, android:layout_above android:layout_above – Aligns the widget next to another widget by using their id.
  • android:layout_marginBottom=”60dp” – Moves the object from the bottom up 60dp. Like the other styles, we can move left, right, top, and bottom
  • dp – dp is a standard a measurement that’s used in Android so that your app will always look the same no matter the screen size of your user.
  • android:layout_centerHorizontal=“true”, android:layout_centerVertical=“true” As you might expect, this centers your component horizontally and vertically.

So now it’s time to write some code in our HelloActivity that we looked at before.  We’re adding on to what we have here.

 

package net.joshchang.josh.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HelloActivity extends AppCompatActivity {
    // Use fields so you can access your widgets at any point in the code
    private EditText mEtText;
    private Button mBtnShow;
    private TextView mTvDisplay;

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

        // 1) Gets access to the widget in the layout via their unique ID's
        mEtText = (EditText) findViewById(R.id.editText);
        mBtnShow = (Button) findViewById(R.id.button);
        mTvDisplay = (TextView) findViewById(R.id.textView);

        // 3) Sets a listener to run your code whenever someone clicks your button.
        mBtnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // gets the text that the user added  in the Edit Text
                String text = mEtText.getText().toString();

                // only set the TextView to the new word if it's not empty
                if (text.length() != 0) {
                    // sets the textview to be the new text
                    mTvDisplay.setText(text);
                    // empty your Edit Text for convenience
                    mEtText.setText("");
                }
            }
        });
    }
}

So let’s step through the new code at each numbered section in the code

  • findViewById(R.id. R.id.editText)gets the object inside the layout with the ID editText
    1. R is a shortcut for your res folder, which as you recall, includes styles, Strings, images, and Id’s
    2. It is also important to note that you have to cast the object you found to the appropriate object. If you don’t you won’t be able to use the proper functions of the widget.
  • Here we create an on click listener on our button. What that means is that every time someone clicks our button, we would execute the code we wrote.

Go ahead and run your code on the emulator. You should see something like this.

9WhatAppLooksLike

And there we go! Our simple List app is finished. But before we finish, there are some things that we can do to make life easier for us!

Previously we’ve been creating a Listener for our button. While the idea is straightforward, writing the code is not. So how can we make this simpler? Turns out, you can add an attribute to your XML file for onClick buttons.

You simply supply it with the name of the method that you want to replace it with and that’s it

hello_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".HelloActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="99dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="148dp"
        android:onClick="AddText" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

 

Our only change was that we added an onClick attribute to our XML and gave it the name of a function that we haven’t defined yet.

So now let’s go create it:

HelloActivity.java

package net.joshchang.josh.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HelloActivity extends AppCompatActivity {
    // Use fields so you can access your widgets at any point in the code
    private EditText mEtText;
    private Button mBtnShow;
    private TextView mTvDisplay;

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

        // 1) Gets access to the widget in the layout via their unique ID's
        mEtText = (EditText) findViewById(R.id.editText);
        mBtnShow = (Button) findViewById(R.id.button);
        mTvDisplay = (TextView) findViewById(R.id.textView);
    }

    // Used by our button in our XML
    public void AddText(View v) {
        // gets the text that the user added  in the Edit Text
        String text = mEtText.getText().toString();

        // only set the TextView to the new word if it's not empty
        if (text.length() != 0) {
            // sets the textview to be the new text
            mTvDisplay.setText(text);
            // empty your Edit Text for convenience
            mEtText.setText("");
        }
    }
}

We replaced our previous button Listener code and instead added the code to our new AddText method.

This code is completely equivalent and much easier to do than to try and remember everything you have to type for the onClickListener.

For the complete code, you can check out the code on my Android Tutorial Github

If you have any questions or suggestions, please drop a message in the comment!

 

Subscribe To Our Weekly Newsletter!
Like these coding articles? Join my mailing list for the latest updates and influence the code that I write!
We hate spam. Your email address will not be sold or shared with anyone else.

Leave a Reply

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