This class teaches you how to build your first Android app. You’ll learn how to create an Android project and run a debuggable version of the app. You'll also learn some fundamentals of Android app design, including how to build a simple user interface and handle user input.
Before you start this class, be sure that you have your development environment set up. You need to:
- Download the Android SDK Starter Package.
- Install the ADT plugin for Eclipse (if you’ll use the Eclipse IDE).
- Download the latest SDK tools and platforms using the SDK Manager.
If you haven't already done this setup, read Installing the SDK. Once you've finished the setup, you're ready to begin this class.
This class uses a tutorial format that incrementally builds a small Android app in order to teach you some fundamental concepts about Android development, so it's important that you follow each step.
1. Creating an Android Project
An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy to start a new Android project with a set of default project directories and files.
This lesson shows how to create a new project either using Eclipse (with the ADT plugin) or using the SDK tools from a command line.
Note: You should already have the Android SDK installed, and if you're using Eclipse, you should have installed the ADT plugin as well. If you have not installed these, see Installing the Android SDK and return here when you've completed the installation.
Create a Project with Eclipse
- In Eclipse, select File > New > Project. The resulting dialog should have a folder labeled Android. (If you don’t see the Android folder, then you have not installed the ADT plugin—see Installing the ADT Plugin).
- Open the Android folder, select Android Project and click Next.
- Enter a project name (such as "MyFirstApp") and click Next.
- Select a build target. This is the platform version against which you will compile your app.We recommend that you select the latest version possible. You can still build your app to support older versions, but setting the build target to the latest version allows you to easily optimize your app for a great user experience on the latest Android-powered devices.If you don't see any built targets listed, you need to install some using the Android SDK Manager tool. See step 4 in the installing guide.Click Next.
remark - the last API level i used was 16 - Specify other app details, such as the:
- Application Name: The app name that appears to the user. Enter "My First App".
- Package Name: The package namespace for your app (following the same rules as packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. For this reason, it's important that you use a standard domain-style package name that’s appropriate to your company or publisher entity. For your first app, you can use something like "com.example.myapp." However, you cannot publish your app using the "com.example" namespace.
- Create Activity: This is the class name for the primary user activity in your app (an activity represents a single screen in your app). Enter "MainActivity".
- Minimum SDK: i haved used API 8 which is enough to run on my machine - GT-S5570B android 2.3.4
Click Finish.
Your Android project is now set up with some default files and you’re ready to begin building the app.
Create a Project with Command Line Tools
If you're not using the Eclipse IDE with the ADT plugin, you can instead create your project using the SDK tools in a command line:
- Change directories into the Android SDK’s
tools/
path. - Execute:
android list targets
This prints a list of the available Android platforms that you’ve downloaded for your SDK. Find the platform against which you want to compile your app. Make a note of the target id. We recommend that you select the highest version possible. You can still build your app to support older versions, but setting the build target to the latest version allows you to optimize your app for the latest devices.If you don't see any targets listed, you need to install some using the Android SDK Manager tool. See step 4 in the installing guide. - Execute:
android create project --target <target-id> --name MyFirstApp \ --path <path-to-workspace>/MyFirstApp --activity MainActivity \ --package com.example.myapp
Replace<target-id>
with an id from the list of targets (from the previous step) and replace<path-to-workspace>
with the location in which you want to save your Android projects.
Your Android project is now set up with several default configurations and you’re ready to begin building the app
Tip: Add the
platform-tools/
as well as the tools/
directory to your PATH
environment variable.2. Running Your App
The Android project, includes a default set of "Hello World" source files that allow you to run the app right away.
How you run your app depends on two things: whether you have a real Android-powered device and whether you’re using Eclipse. I will show you how to install and run your app on a real device and on the Android emulator, and in both cases with either Eclipse or the command line tools.
Before you run your app, you should be aware of a few directories and files in the Android project:
AndroidManifest.xml
- This manifest file describes the fundamental characteristics of the app and defines each of its components. You'll learn about various declarations in this file as you read more training classes.
src/
- Directory for your app's main source files. By default, it includes an
Activity
class that runs when your app is launched using the app icon. res/
- Contains several sub-directories for app resources. Here are just a few:
drawable-hdpi/
- Directory for drawable objects (such as bitmaps) that are designed for high-density (hdpi) screens. Other drawable directories contain assets designed for other screen densities.
layout/
- Directory for files that define your app's user interface.
values/
- Directory for other various XML files that contain a collection of resources, such as string and color definitions.
When you build and run the default Android project, the default
Activity
class in the src/
directory starts and loads a layout file from the layout/
directory, which includes a "Hello World" message. Not real exciting, but it's important that you understand how to build and run your app before adding real functionality to the app.Run on a Real Device
Whether you’re using Eclipse or the command line, you need to:
- Plug in your Android-powered device to your machine with a USB cable. If you’re developing on Windows, you might need to install the appropriate USB driver for your device. For help installing drivers, see the OEM USB Drivers document.
- Ensure that USB debugging is enabled in the device Settings (open Settings and navitage to Applications > Development on most devices, or select Developer options on Android 4.0 and higher).
To run the app from Eclipse, open one of your project's files and click Run from the toolbar. Eclipse installs the app on your connected device and starts it.
Or to run your app from a command line:
- Change directories to the root of your Android project and execute:
ant debug
- Make sure the Android SDK
platform-tools/
directory is included in yourPATH
environment variable, then execute:adb install bin/MyFirstApp-debug.apk
- On your device, locate MainActivity and open it.
Whether you’re using Eclipse or the command line, you need to first create an Android Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different device configurations.
To create an AVD:
- Launch the Android Virtual Device Manager:
- In Eclipse, select Window > AVD Manager, or click theAVD Manager icon in the Eclipse toolbar.
- From the command line, change directories to
<sdk>/tools/
and execute:./android avd
- In the Android Virtual Device Device Manager panel, clickNew.
- Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
- Click Create AVD.
- Select the new AVD from the Android Virtual Device Manager and click Start.
- After the emulator boots up, unlock the emulator screen.
To run the app from Eclipse, open one of your project's files and click Run from the toolbar. Eclipse installs the app on your AVD and starts it.
Or to run your app from the command line:
- Change directories to the root of your Android project and execute:
ant debug
- Make sure the Android SDK
platform-tools/
directory is included in yourPATH
environment variable, then execute:adb install bin/MyFirstApp-debug.apk
- On the emulator, locate MainActivity and open it.
3. Building a Simple User Interface
MyFirstApp.zip
The graphical user interface for an Android app is built using a hierarchy of
View
and ViewGroup
objects. View
objects are usually UI widgets such as a button or text field and ViewGroup
objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
Android provides an XML vocabulary that corresponds to the subclasses of
View
and ViewGroup
so you can define your UI in XML with a hierarchy of view elements.I will teach you to create a layout in XML that includes a text input field and a button. In the following section, you'll respond when the button is pressed by sending the content of the text field to another activity.
Use a Linear Layout
Open the
activity_main.xml
file from the res/layout/
directory (every new Android project includes this file by default).
Note: In Eclipse, when you open a layout file, you’re first shown the ADT Layout Editor. This is an editor that helps you build layouts using WYSIWYG tools. For this lesson, you’re going to work directly with the XML, so click the main.xml tab at the bottom of the screen to open the XML editor.
By default, the
main.xml
file includes a layout with a LinearLayout
root view group and a TextView
child view. You’re going to re-use the LinearLayout
in this lesson, but change its contents and layout orientation.
First, delete the
TextView
element and change the value android:orientation
to be "horizontal"
. The result looks like this:<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</LinearLayout>
LinearLayout
is a view group (a subclass of ViewGroup
) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation
attribute. Each child of a LinearLayout
appears on the screen in the order in which it appears in the XML.
The other two attributes,
android:layout_width
and android:layout_height
, are required for all views in order to specify their size.
Because the
LinearLayout
is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "fill_parent"
.
For more information about layout properties, see the XML Layout guide.
Add a Text Field
To create a user-editable text field, add an
<EditText>
element inside the <LinearLayout>
. The EditText
class is a subclass of View
that displays an editable text field.
Like every
View
object, you must define certain XML attributes to specify the EditText
object's properties. Here’s how you should declare it inside the <LinearLayout>
element: <EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
About these attributes:
android:id
- This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
The at-symbol (@
) is required when you want to refer to a resource object from XML, followed by the resource type (id
in this case), then the resource name (edit_message
). (Other resources can use the same name as long as they are not the same resource type—for example, the string resource uses the same name.)The plus-symbol (+
) is needed only when you're defining a resource ID for the first time. It tells the SDK tools that the resource ID needs to be created. Thus, when the app is compiled, the SDK tools use the ID value,edit_message
, to create a new identifier in your project'sgen/R.java
file that is now assiciated with theEditText
element. Once the resource ID is created, other references to the ID do not need the plus symbol. This is the only attribute that may need the plus-symbol. See the sidebox for more information about resource objects. android:layout_width
andandroid:layout_height
- Instead of using specific sizes for the width and height, the
"wrap_content"
value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use"fill_parent"
, then theEditText
element would fill the screen, because it'd match the size of the parentLinearLayout
. For more information, see the XML Layouts guide. android:hint
- This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the
"@string/edit_message"
value refers to a string resource defined in a separate file. Because this value refers to an existing resource, it does not need the plus-symbol. However, because you haven't defined the string resource yet, you’ll see a compiler error when you add the"@string/edit_message"
value. You'll fix this in the next section by defining the string resource.
Add String Resources
When you need to add text in the user interface, you should always specify each string of text in a resource file. String resources allow you to maintain a single location for all string values, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string.
By default, your Android project includes a string resource file at
res/values/strings.xml
. Open this file, delete the existing "hello"
string, and add one for the "edit_message"
string used by the <EditText>
element.
While you’re in this file, also add a string for the button you’ll soon add, called
"button_send"
.
The result for
strings.xml
looks like this:<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
For more information about using string resources to localize your app for several languages, see the Supporting Various Devices class.
Now add a
<Button>
to the layout, immediately following the <EditText>
element: <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
The height and width are set to
"wrap_content"
so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id
attribute, because it won't be referenced from the activity code.Make the Input Box Fill in the Screen Width
The layout is currently designed so that both the
EditText
and Button
widgets are only as big as necessary to fit their content, as shown in figure 2.
This works fine for the button, but not as well for the text field, because the user might type something longer and there's extra space left on the screen. So, it'd be nice to fill that width using the text field.
LinearLayout
enables such a design with the weight property, which you can specify using the android:layout_weight
attribute.
The weight value allows you to specify the amount of remaining space each view should consume, relative to the amount consumed by sibling views, just like the ingredients in a drink recipe: "2 parts vodka, 1 part coffee liquer" means two-thirds of the drink is vodka. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view gets 2/3 of the remaining space and the second view gets the rest. If you give a third view a weight of 1, then the first view now gets 1/2 the remaining space, while the remaining two each get 1/4.
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after each view is given the space it requires. So, to fill the remaining space with the
EditText
element, give it a weight of 1 and leave the button with no weight. <EditText
android:layout_weight="1"
... />
In order to improve the layout efficiency when you specify the weight, you should change the width of the
EditText
to be zero (0dp). Setting the width to zero improves layout performance because using"wrap_content"
as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space. <EditText
android:layout_weight="1"
android:layout_width="0dp"
... />
Figure 3 shows the result when you assign all weight to the
EditText
element.
Here’s how your complete layout file should now look:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>
This layout is applied by the default
Activity
class that the SDK tools generated when you created the project, so you can now run the app to see the results:- In Eclipse, click Run from the toolbar.
- Or from a command line, change directories to the root of your Android project and execute:
ant debug adb install bin/MyFirstApp-debug.apk
Continue to the next lesson to learn how you can respond to button presses, read content from the text field, start another activity, and more.
4. Starting Another Activity
After completing the previous section, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to
MainActivity
that starts a new activity when the user selects the Send button.
Respond to the Send Button
To respond to the button's on-click event, open the
main.xml
layout file and add the android:onClick
attribute to the<Button>
element:<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
The
android:onClick
attribute’s value, sendMessage
, is the name of a method in your activity that you want to call when the user selects the button.
Add the corresponding method inside the
MainActivity
class:/** Called when the user selects the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
Note that, in order for the system to match this method to the method name given to
android:onClick
, the signature must be exactly as shown. Specifically, the method must:- Be public
- Have a void return value
- Have a
View
as the only parameter (this will be theView
that was clicked)
Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.
Build an Intent
An
Intent
is an object that provides runtime binding between separate components (such as two activities). The Intent
represents an app’s "intent to do something." You can use an Intent
for a wide variety of tasks, but most often they’re used to start another activity.
Inside the
sendMessage()
method, create an Intent
to start an activity called DisplayMessageActvity
:Intent intent = new Intent(this, DisplayMessageActivity.class);
The constructor used here takes two parameters:
- A
Context
as its first parameter (this
is used because theActivity
class is a subclass ofContext
) - The
Class
of the app component to which the system should deliver theIntent
(in this case, the activity that should be started)
Note: The reference to
DisplayMessageActivity
will raise an error if you’re using an IDE such as Eclipse because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.
An intent not only allows you to start another activity, but can carry a bundle of data to the activity as well. So, use
findViewById()
to get the EditText
element and add its message to the intent:Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
An
Intent
can carry a collection of various data types as key-value pairs called extras. The putExtra()
method takes a string as the key and the value in the second parameter.
In order for the next activity to query the extra data, you should define your keys using a public constant. So add the
EXTRA_MESSAGE
definition to the top of the MyainActivity
class:public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE";
...
}
It's generally a good practice to define keys for extras with your app's package name as a prefix to ensure it's unique, in case your app interacts with other apps.
Start the Second Activity
To start an activity, you simply need to call
startActivity()
and pass it your Intent
.
With this method included, the complete
sendMessage()
method that's invoked by the Send button now looks like this:/** Called when the user selects the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Now you need to create the
DisplayMessageActivity
class in order for this to work.Create the Second Activity
In your project, create a new class file under the
src/<package-name>/
directory called DisplayMessageActivity.java
.
Tip: In Eclipse, right-click the package name under the
src/
directory and select New > Class. Enter "DisplayMessageActivity" for the name and android.app.Activity
for the superclass.
Inside the class, add the
onCreate()
callback method:public class DisplayMessageActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
All subclasses of
Activity
must implement the onCreate()
method. The system calls this when creating a new instance of the activity. It is where you must define the activity layout and where you should initialize essential activity components.Add it to the manifest
You must declare all activities in your manifest file,
AndroidManifest.xml
, using an <activity>
element.
Because
DisplayMessageActivity
is invoked using an explicit intent, it does not require any intent filters (such as those you can see in the manifest for MainActivity
). So the declaration forDisplayMessageActivity
can be simply one line of code inside the <application>
element:<application ... > <activity android:name="com.example.myapp.DisplayMessageActivity" /> ... </application>
The app is now runnable because the
Intent
in the first activity now resolves to theDisplayMessageActivity
class. If you run the app now, pressing the Send button starts the second activity, but it doesn't show anything yet.Receive the Intent
Every
Activity
is invoked by an Intent
, regardless of how the user navigated there. You can get the Intent
that started your activity by calling getIntent()
and the retrieve data contained within it.
In the
DisplayMessageActivity
class’s onCreate()
method, get the intent and extract the message delivered by MainActivity
:Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
To show the message on the screen, create a
TextView
widget and set the text using setText()
. Then add theTextView
as the root view of the activity’s layout by passing it to setContentView()
.
The complete
onCreate()
method for DisplayMessageActivity
now looks like this:@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
You can now run the app, type a message in the text field, press Send, and view the message on the second activity.
That's it, you've built your first Android app!
4. Debug Your App
You can debug yout application using e.g. breakpoints. you simple go to the code line and click twice on the left side to get :
Next you need to use "Debug As" for running the application under the debugger
The breakpoint is hit and you can check values or continue using the circled icons :
The following app was published using this post.
Nathan
I'm having a hard time with the "Building a Simple User Interface" part...
ReplyDeleteI get two errors:
1. No resource found that matches the give name (at 'label' with value '@string/title_activity_my_first').
2. Unparsed aapt error(s)! Check the console for output.
Can anyway decipher what this means? And how I might be able to fix it?
Hi
DeleteHave you downloaded MyFirstApp.zip ?
Nathan