Robert Wenger's Computing and Tech Blog

The Beginner’s Guide for Android Development

Don’t know how to program for Android? If you’re a programmer, you should probably learn. Android currently runs on approximately 50% of smartphones out there (Jan 2014 Comscore), more than any other mobile operating system. Android also runs on other devices from tablets to even cameras, making android an easy choice for a mobile platform for your app.

So how do you program an Android app? Click here if you are familiar with Java. Otherwise, read on!

Java Logo

Java Logo

Learn the Language

Android apps are programmed using Java, a very popular Object Oriented Programming Language. There are many tutorials for Java, so I won’t go into detail about how to program in Java here, but this is how you should get started with Java.

Download Eclipse

Eclipse is a popular Integrated Development Environment (IDE), which is a tool used to assist with programming. It contains error checking, auto-completion, compilation, support for plugins, and a lot more. You’re going to want to get used to Eclipse, because we will be using it along with some Android tools to get Android apps running.

In the past I have had to download Eclipse separately from the Android tools in order to begin development, but Google now offers an all in one bundle which includes Eclipse and all of the necessary tools to get started. Download the ADT Bundle for Windows, install it, and you’re done!

Installation Instructions

Follow Some Java Tutorials

If you are familiar with Java, feel free to skip this section. Before I get into this section any more, here are a couple of tutorials to follow:

I have found YouTube videos to be very helpful for learning various things related to Android. Here’s one which should give you a quick example of programming in Java from within Eclipse.

As you can see, there are a wide range of resources out there for someone learning Java. Find one that you like, and you should be fine. Once you have a grasp of the basics of Java, the Java documentation should have all of the information you need on various parts of the Java language.


Installing Android Support

I covered an all in one package with Eclipse and the Android tools above, but if you want to install the development tools on top of an existing Eclipse install, follow this link and look under “Use an Existing IDE”:

Android SDK

Then, install the ADT Plugin.. Again, if you have already installed the bundle from the earlier section, you do not need to do this.

Programming for Android

There are a number of different facets of Android programming, so we’ll start with what you see on the screen. From this point on, I’ll assume you have a decent understanding of Java programming. If not, check out the tutorials I posted above.

Android Projects

Starting an Android application in Eclipse is easy. Just click File > New > Android Application Project.

Click File > New > Android Application Project

Click File > New > Android Application Project

On the screen that pops up, look for a text box labeled “Application Name”. Type the name of your app in the input box. This is the name that will appear in your app and in the Google Play Store if you decide to distribute your app. Then, select the “Holo Light” theme.

Name your app, then click next.

Name your app, then click next.

On the next screen, deselect “Create custom launcher icon” and “Create activity”. We will be creating our activity a little later. Click finish to create your project.

Deselect the checkboxes "Create custom launcher icon" and "Create activity"

Deselect the checkboxes “Create custom launcher icon” and “Create activity”, then press finish.

Now that we have our first Android project, let’s start editing things.

Android Layouts

All of the components of your app must be laid out with some sort of organization. This is where Android’s layouts come into play. The Android documentation for layouts says

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:

  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
  • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.

So, there are two different ways of creating layouts – XML and dynamically. For now, we’ll stick with XML.

To create your first layout, right click on the layout folder (App Name > res > layout) in the Package Explorer, choose New, and select “Android XML File”.

Creating a new layout.

Creating a new layout.

In the window that appears, type the name of the XML layout (I’m using layout_main) and click finish.

Type the filename of your new layout and click finish.

Type the filename of your new layout and click finish.

Your new XML file should open when you click finish. If it doesn’t open, open it from the layout folder. You should see something like this:

The layout editor.  Click the highlighted tab to see the XML.

The layout editor. Click the highlighted tab to see the XML.

The screen you see is a visual editor. You can click things from the menu on the left and drag them onto the screen shown on the right. This can be very useful and can save you some time, but we’re interested in the actual code behind the layout. Click the tab shown in the image above to see the XML for your new layout.

You should see some code that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

The main thing to notice here is that LinearLayout is a type of layout. This type of layout displays things on the screen linearly. This LinearLayout has a vertical orientation, so this layout displays the first thing it contains, or it’s first child, at the top of the screen. Then, the layout displays the next child below the first, and so on. The last child is displayed at the bottom of the screen. This layout is the parent displaying its children from top to bottom. If the LinearLayout had a horizontal orientation, the children would be displayed from left to right.

There are, of course, more options of how to align things on the screen, but we can’t talk about all of them here. I’ll focus on the LinearLayout in this guide. Check out the documentation for layouts I quoted earlier to check out the various types of layouts.

Now, note that this layout has certain attributes that specify how it behaves. This bit of code has the layout_width, layout_height, and orientation attributes. The height and width attributes are both set to match_parent; this means that the the layout will take up the entire screen.

Now these layouts are great, but a layout doesn’t do anything by itself. We need to add some children to make things happen. Let’s add some text, an input box, and a button. To do this, you could drag some elements in using the visual editor, but let’s do it programmatically.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/prompt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Enter text to display here:" />

    <EditText
        android:id="@+id/textBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:inputType="text" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Show me!" />
</LinearLayout>

Note that these new elements are placed within the opening and closing LinearLayout tags. If you check out the visual layout editor, you should see something like this:

The layout with children added.

The layout with children added.

As you can see, we now have three children laid out from top to bottom. Let’s examine the code for these three elements individually.

    <TextView
        android:id="@+id/prompt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Enter text to display here:" />

A TextView is simply something that displays text on the screen. Like the layout, it has its own parameters. The width is set to match_parent. In this case, the TextView is a child of the LinearLayout, which means it is the same width as the layout. The layout matches the width of the screen, so the TextView element will also be the same size as the screen. The height is set to wrap_content. This means that the TextView will only be as tall as it needs to be in order to contain the text. That isn’t very tall, as you can see from the image above.

The TextView has a gravity attribute set to center. This means that the text will be centered in the TextView. The text is set in the text attribute, and we get what you see in the image.

    <EditText
        android:id="@+id/textBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

An EditText element is an input box where the user can type things. The width and height attributes are the same as those of the TextView, so they have the same effects. The inputType attribute lets us specify what type of input we want from this EditText. For example, we could use “password” as the input type and the user’s input would be hidden for security.

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Show me!" />

Finally, we have a Button. The Button element is simply a button that the user can press. The text attribute specifies the text on the face of the button.

On all of these elements, we have the id attribute. This lets us find the element when we need it. Where will we need it? In an activity, of course.

Android Activities

From the Android documentation for activities:

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI…

An activity is a Java class that provides an interface to interact with your app. They can use other functions to do other things, but it must have an interface. Now that we have the layout for our interface, let’s get to work on making the layout do useful things.

First, we must create a class for our activity. Right click on the source folder for your project, select new, and click Class.

Creating a new class in Android.

Creating a new class in Android.

Then, we must set up our class. Give your class a name (I’m using MainActivity – a fairly common name for the class containing the first activity of an app). Then, set the superclass to android.app.Activity. Click finish.

Set up the class as shown.

Set up the class as shown.

Open the newly-created file, and let’s see what we have.

import android.app.Activity;

public class MainActivity extends Activity {

}

That’s not much, but it’s a start. Now that our class inherits the methods of the Activity class, we can use all of its methods. One of these methods is call onCreate. When our Activity starts for the first time, the onCreate method is called. This is how we set up the things we will need for our app. Here’s what it looks like:

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		
	}

The Activity class already defines onCreate, which means we must override it to make it do what we want it to instead of what it’s already set up to do. We override methods using @Override before the method we want to override. Ignore the parameter for now – we won’t be using it now. Just not the syntax of this block of code.

The parameter uses a class called Bundle. If you copy and paste this code, make sure to import it the same way Activity is imported above.

import android.os.Bundle;

Now insert this line:

super.onCreate(savedInstanceState);

This calls the onCreate method in the Activity. Even though we’re overriding that method, we still need that method to run in order for our app to be set up correctly.

Now that we’re getting the app set up correctly, let’s get our layout and set up the activity to interface with the layout. The first thing we have to do is set up some references to our elements in the layout. Remember the layout has three children – a text display (TextView), an input box (EditText), and a button (Button). So in the class, we will need three variables.

	private TextView textDisplay;
	private EditText inputBox;
	private Button button;

Of course, we haven’t set those variables yet, so we’ll have to set them up in the onCreate method. The Activity class has a convenient method called findViewById which can help us.

		textDisplay = (TextView)findViewById(R.id.prompt);
		inputBox = (EditText)findViewById(R.id.inputBox);
		button = (Button)findViewById(R.id.button);

Now if you’ve followed what I’ve done so far, you should probably get an error here along the lines of “R cannot be resolved to a variable”. The code is correct, but the project isn’t set up quite the way it needs to be. Open AndroidManifest.xml (shown below).

Opening AndroidManifest.xml

Opening AndroidManifest.xml

This is an XML file used to store the settings of the app. If something isn’t working and your Java code seems correct, it’s a good idea to check the settings in the manifest. The line that’s causing problems is this line:

    package="com.example.blogpostapp"

Android applications need to be in a unique package. When we created our Activity, we neglected to add a package. Now, we need to put it in the correct package, in this case “com.example.blogpostapp”. To do this, right click on the src folder, select new, and click Package.

Create a new package.

Create a new package.

Next, name your package and click finish.

Naming a package.

Naming a package.

Now, drag your Activity into the newly-created package, and you’re done.

Drag your Activity to your new package.

Drag your Activity to your new package.

The error should now disappear. Note that this problem could have been avoided by specifying the package name when we created the Activity (examine this image). However, it’s good to learn how to diagnose problems with your project setup, and problems involving R can sometimes be rather vexing.

Now that we’re back on track, let’s take a look at our Activity so far:

package com.example.blogpostapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
	
	private TextView textDisplay;
	private EditText textBox;
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		textDisplay = (TextView)findViewById(R.id.prompt);
		textBox = (EditText)findViewById(R.id.textBox);
		button = (Button)findViewById(R.id.button);
	}
}

We’re getting there. We have references to the elements of our project, so we can now do things with them. But if we run our app, we’re still not going to see the layout. To see the layout, your activity must set the current layout using a method called setContentView.

setContentView(R.layout.layout_main);

When we open our app now, we’ll see the layout we made earlier. However, it won’t do anything yet. We must add a few more pieces to make things happen.

What do we want to happen? With this app, the user should type something into an input box. Then, when they press the button, we can grab the data from the input box and use it somehow. The first thing we need to do is know when the user presses the button.

To do this, we need to set a click listener for the button. When the button is pressed, it will notify all of its listeners of the action so that they can act accordingly. We can make our activity listen to the button so that it gets updates on actions for the button.

Here’s how we do it:

package com.example.blogpostapp;

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


public class MainActivity extends Activity implements OnClickListener{
	
	private TextView textDisplay;
	private EditText textBox;
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_main);
		
		textDisplay = (TextView)findViewById(R.id.prompt);
		textBox = (EditText)findViewById(R.id.textBox);
		button = (Button)findViewById(R.id.button);
		
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
}

There are three new things in this code.

First, we set the listener in the onCreate method. This method registers the listener passed into the method as a listener for the button. In this case, the listener is the current ActivityMain class.

Next, we need to make the class implement the listener interface. When a class implements a listener interface (such as OnClick), it can then be used as a listener for all sorts of elements which support the action in question (such as a Click, Touch, etc).

Finally, we need to create the onClick method. OnClick is called when an element the current class is listening to is clicked. The element that sent the message is passed as a parameter to onClick because a class can listen to multiple elements. For example, if we had a “clear text” button, we could set its listener to the activity too. Then, we would check which button is clicked and perform the appropriate actions. We perform this check by using this code:

	if(v == button)
	{
		// Do something.
	}

So now we know how to check when the button is pressed. To get the data of the EditText input box, we can use the getText method.

String inputText = textBox.getText().toString();

Now, we can do anything we want with the input. For now, let’s display it to the screen. There is a class called Toast with which you can display short messages to the user. We use it like this:

Toast.makeText(this, inputText, Toast.LENGTH_LONG).show();

And we’re done! The final result should look like this:

package com.example.blogpostapp;

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


public class MainActivity extends Activity implements OnClickListener{
	
	private TextView textDisplay;
	private EditText textBox;
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_main);
		
		textDisplay = (TextView)findViewById(R.id.prompt);
		textBox = (EditText)findViewById(R.id.textBox);
		button = (Button)findViewById(R.id.button);
		
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if(v == button)
		{
			String inputText = textBox.getText().toString();
			Toast.makeText(this, inputText, Toast.LENGTH_LONG).show();
		}
		
	}
}

This code will only display the user’s input on the screen for a moment, and it isn’t particularly useful. Of course, there are countless ways to get data, and there are also countless ways to use that data to create meaningful apps that can help your users. This example shows how an app is structured, but it is your job as the programmer to make it helpful for the people who use your app.

We’re done with our activity, but we’re not quite ready to test our app yet. There are still a few things we need to fix in the manifest.

Fixing the Manifest

The manifest holds various settings, and among them is a listing of all of the activities in the app and settings for each one. We haven’t added our activity to our manifest yet, so if we load the app on the phone in its current state, it won’t know what to run. We must make sure all of our activities (in this case we only have one) are accounted for in our manifest before we can run them.

To do this, first open the manifest as described above. Then add the following between the opening and closing application tags:

<activity
    android:name="com.example.blogpostapp.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Now, your app is ready to run. Let’s test it.

Running Your App

For this guide, I’ll assume you have an Android phone to test your code with. If you don’t, check out the Android Emulator. I would advise running your applications on an actual phone if possible, because not only is this how your application will be run in real situations, but the emulator can be slow and lacks the support of sensors and the camera. With that said, the emulator is out there if you have no device whatsoever with which to run your app.

To run your app on your phone, first go to the system settings on your phone. Scroll to the bottom, then select Developer Options. Turn developer options on. Then, check the box for USB Debugging. This allows you to not only run your app, but it allows you to see helpful information in Eclipse in case your app crashes.

Enabling debugging for Android.

Enabling debugging for Android.

Now, in Eclipse, run your app. Click the play button at the toolbar.

Click the play button to run your app.

Click the play button to run your app.

If prompted, run your app as an Android application.

Select "Android Application".

Select “Android Application”.

Finally, select your device from the list and click ok.

Select your phone, then click ok.

Select your phone, then click ok.

Your app will now run on your phone. You’ve done it, you’ve created a working Android app!

Our app in action!

Our app in action!

Did you use this guide to help create an Android app? Have a question about Android development? I’d love to hear what you have to say! Leave a comment below.

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

*


*