Java Android Tutorial

Guest Posts David McMahon

As mobile technology is advancing in popularity, at a rapid rate, Android programming is becoming more and more of an essential skill to acquire. Not only does it look good on your CV for a job interview but can be of benefit for personal use as well. Android is a Linux-based operating system (OS) for programming devices such as smart phones or tablets. The good news is that, if you have an understanding of Java programming, then Android programming should be relatively easy for you to adopt as it is written in the Java language. If you do not have an understanding of Java programming or are new to programming in general then check out this free Java For Complete beginners course first. If you like being thrown into the deepened however, then proceed on reading!

Java For Complete Beginners

This article will get you up and running with your first Android Application and introduce you to some fundamental concepts about the subject.

For this article I will be using eclipse as my IDE and you can install an ADT plugin for eclipse that will enable you to start writing android code at your leisure. The Android Software Development Kit is used to develop the applications through the Java language. Both will need to be downloaded.

Jargon Buster


  • Activities:  These handle the user interaction and dictate the UI (User Interface Screen)



  • Services: These handle the background processing associated with the application



  • XML View: This view is used to design the UI and layout the components such as Buttons, TextViews and RadioGroups.



  • Main Activity: Similar to the main method in Java programs, the application starts here. Your MainActivity, which can be named to whatever you wish, extends Activity to make use of the built in methods used to create and run the app.


Now that we have some of the technical jargon down, lets get onto some coding.

Click New - Android - Android Application Project - Next

You can fill in the Application Name, Project Name and Package Name to your liking and click Next

Accept the defaults for the next few pages. When you reach Create Activity select Blank Activity and click Next. Accept the default name for the activity which should be MainActivity and the default Layout which should be activitymain.

Eclipse will open up the MainActivity.java and activity
main.xml. if it doesn't then do not worry. You can find activitymain.xml under res/layout/mainactivity.xml

We will be working directly from these two windows. The MainActivity.java will handle our logical code and the activitymain.xml will handle our UI Design. Having these in two separate files increases readability and makes troubleshooting a lot easier for when your application becomes complex. Any components you will be adding onto your application such as Buttons or TextViews will be coded in through the activitymain.xml file. Some programmers use the Graphical Layout, which you can find on the bottom left of your activity_main.xml file, but I do not favor this way of designing in real life as an understanding of xml is crucial.
MainActivity.java

 package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

} 

Above is what your MainActivity file should look like.

And this is what your activity_main should look like:

 
<RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
 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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>
 

Go ahead and delete the TextView inside the activitymain.xml file and its properties as we will create our own later. Also go ahead and change the opening and closing RelativeLayout tags to LinearLayout tags respectively.

Your activity
main.xml should now look like this

 
<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: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" >
</LinearLayout>
 

Adding two buttons to the UI design

 
<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=".MainActivity" >

    <Button
        android:id="@+id/hello_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="@string/hello" />

    <Button
        android:id="@+id/goodbye_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/goodbye" />
 

As you can see the method of adding components to the application is relatively easy. We open a Button tag, eclipse users type Ctrl + Space to auto finish the tag, and place properties in the middle of the tag. I will break down the properties and explain them to the best of my knowledge:

android:id - This is a unique identifier we use on the component to be able to reference it later in our logical MainActivity.java file. The @ sign is required when referring to any resource object in XML such as a string or layout. More on this later.
android:layoutwidth - Sets the width that the component should occupy, in this case I set it to fill parent which makes it fill the length of the device.
android:layout
height - Sets the height the component should occupy, here I set it to wrapcontent which means it takes up as much space as the text on it is needed.
android:layout
marginBottom - Sets the space that the component should take up from the next component below it.
android:text - This sets the text on the button. In this case the @ sign is used which, if you remember, refers to any resource object. In this case we are referring to the strings.xml file and calling the string which has a name of hello. At this point I think its important to have a look at the strings.xml file. It can be located at values/strings.xml.

If you open it up you should see this:

 
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Test</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

</resources>

 

You can go ahead and delete the line that says Hello world! as we deleted the textView that called that string. Any name that you place on a component should be defined in this strings.xml file first. Give it a name and then give it the text in which you want the component to have. In the example Button above I set the android:text="@string/hello" so in our strings.xml file we enter in a new string with a name of 'hello' and the text we want to be placed on the button after it such as 'Hello'. Now back in our activity_main.xml file we can read the android:text line as follows, refer to the string in the strings.xml file with a name of hello. It will then go to the strings.xml file, locate the string with a name of hello and set that text onto our button. Pretty cool eh? This is the power of XML in action.

We then add another button with an Id of goodbyeButton and set the text to @string/goodbye. Yes you guessed it, go back into your strings.xml file and add a new string with a name of 'goodbye' and the text you want to appear on the Button after it.

Your strings.xml file should now look like this:

 
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Test</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
   <string name="goodbye">GoodBye!</string>

</resources>
 

Remember, so far all we have been doing is designing our UI. We will get to the logical coding bit soon to make the buttons do something. So buckle up!

We will now add a TextView to the UI so go back into the activitymain.xml and open a tag with TextView inside it and close it off also. The properties will go in between the tags after the word TextView.
Try this yourself before looking at my code below and see if you can figure it out based on the two buttons above! Give the TextView a unique ID of view
buttontext, set the layoutwidth to span across the wntire width of the screen, set the layoutheight to span as needed indicated by text, add a 'hint' to the TextView which will reference a string in the strings.xml file that says "text to go here" when called.

Can you do it? If so then Well done! If not then do not worry as it took me several weeks to get my head around it, so stick with it! :)

Here is the code that should be inside your activity
main.xml file now:

 
<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=".MainActivity" >

    <Button
        android:id="@+id/hello_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="@string/hello" />

    <Button
        android:id="@+id/goodbye_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/goodbye" />

<TextView
        android:id="@+id/view_button_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint"
        android:paddingBottom="100dp"
        android:paddingLeft="100dp"
        android:paddingTop="100dp" />

</LinearLayout>

 

You will notice I added paddingBottom, paddingLeft and paddingTop to the TextView. This is purely for layout purposes as you will see when you run the app later. Padding is the space the text takes up inside the component. It cannot take a direct number such as Float or Int, it needs a pixel value depicted by dp so a value of 100dp would be 100 pixels.
We are now done coding out UI design. Lets switch over to the MainActivity.java file and start coding some functionality to the Buttons and TextView.

Go into the onCreate() method in the MainActivity.java file and here is where we will be adding the code that gets run when your application is ran. First of all we have to create 3 objects, 2 for each Button and 1 for the TextView. Now this is similiar to the way you create object in Java but hold on a second there is one small difference. Since we designed our components in XML how does our MainActivity.java file now which button we were talking about? Well remember the unique ID we set for all our components, now it where that comes in handy to differentiate between components. We can use the findViewById() method and pass it in the id of our component. For example, creating the Button object would be as follows:

 Button helloButton = findViewById(R.id.helloButton); 

This means find the component with the Id name of helloButton in the /res folder and set it equal to the object of Button. Now our Button object knows which button to reference, if you are getting an error message at this point then don't worry, the reason for this is you need to typecast method to type Button. So our final line will look like this:

 Button helloButton = (Button) findViewById(R.id.helloButton); 

Do this for each of the components you created in the XML file, the other Button and the TextView. Try it without looking at my code below first.

MainActivity.java

 package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        Button helloButton = (Button) findViewById(R.id.hello_button);
        Button goodbyeButton = (Button) findViewById(R.id.goodbye_button);
        final TextView textView = (TextView) findViewById(R.id.view_button_text);

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

} 

That is what your MainActivity should now look like. Now each object knows which component to reference in the XML activity_main.xml file so we can use them in our code now. Lets make it so when the helloButton is clicked then "Hello" is emitted onto the textView and when goodbyeButton is clicked, yes you guessed it, goodbye will be emitted onto the textView. To do this is the same way we do it in Java really. We put two listeners onto the Buttons to execute some piece of code when the button is clicked. I will use an anonymous inner class for this as most Java programmers will be used to this method.

MainActivity.java

 package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        Button helloButton = (Button) findViewById(R.id.hello_button);
        Button goodbyeButton = (Button) findViewById(R.id.goodbye_button);
        final TextView textView = (TextView) findViewById(R.id.view_button_text);
        Button resetButton = (Button) findViewById(R.id.reset_button);

        helloButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("");
                String message = "Hello, World of Android";
                textView.append(message + "\n");
            }
        });

        goodbyeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("");
                String message = "GoodBye, World of Android";
                textView.append(message + "\n");
            }
        });

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

} 

This is what you should have in your MainActivity.java class now. If you are getting erros then eclipse users hit Ctrl+Shift+o to add the import or cmd+shift+o on Mac's. Here we are just adding two OnClickListeners to our buttons and creating a new OnClickListener with the overridable onClick() method within. Be careful!! Eclipse users if you type Ctrl+Space to auto type the inner class, it will not put the semi-colon needed after the closing parenthesis for the setOnClickListener method.

Now inside the onClick() method we place the code we want to happen. This should look some bit familiar to you if you have experience with Java anyway. For the goodbyeButton we simply start of by setting the textViewtext to an empty string, Store a string inside the variable message and then set the textViewText with that message variable. You can use setTextViewText() or append(), it dosent really matter but because I am setting the text of the textView to an empty string when the button is clicked maybe it would have been more logical to use the setTextViewText() instead of append() as we are not technically appending onto it.

And thats it folks, you can run your ActivityMain.java on Eclipse but remember to start your Android Virtual Device first or it will not run. This was a very basic program but it had ALOT going on in it. I hope it was a good learning experience and if you want to learn more about Android Programming then follow this link: