page.title=Hello, World @jd:body
As a developer, you know that the first impression of a development framework is how easy it is to write "Hello, World." Well, on Android, it's pretty easy. It's particularly easy if you're using Eclipse as your IDE, because we've provided a great plugin that handles your project creation and management to greatly speed-up your development cycles.
If you're not using Eclipse, that's okay. Familiarize yourself with Developing in Other IDEs. You can then return to this tutorial and ignore anything about Eclipse.
Before you start, you should already have the very latest 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.
Note: If you're developing with an Android SDK older than the one provided for Android 1.5, you can skip this step and continue with Create the Project.
In this tutorial, you will run your applicion in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD, use the android
tool provided in the Android SDK.
Open a command prompt or terminal, navigate to the
/tools
directory in the SDK package and execute:
android create avd --target 1 --name myavd
The tool now asks if you would like to create a custom hardware profile, say
no
. That's it. You now have an AVD and can use it to run the Emulator.
In the above command, the target
option is required
and specifies the target platform for the emulator. (A target defines the system image,
API level and supported skins. To view all available targets, execute:
android list target
.) The name
option is also required
and defines the name for the new AVD. For more information about android
,
see the Android Tool
documentation.
From Eclipse, select the File > New > Project menu item. If the Android Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain a single entry: "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
Selected "Android Project" and click Next.
The next screen allows you to enter the relevant details for your project:
Click Finish.
Here is a description of each field:
Your package name must be unique across all packages installed on the Android system; for this reason, it's very important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.
Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files will be generated and stored. "Target" is the platform target for your application.
Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this:
package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Notice that the class is based on the {@link android.app.Activity} class. An Activity is a single application entity that is used to perform actions. An application may have many separate activities, but the user interacts with them one at a time. The {@link android.app.Activity#onCreate(Bundle) onCreate()} method will be called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup. An activity is not required to have a user interface, but usually will.
Now let's modify some code!
Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added.
package com.android.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } }
Tip: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you.
An Android user interface is composed of hierarchies of objects called Views. A {@link android.view.View} is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is {@link android.widget.TextView}.
In this change, you create a TextView with the class constructor, which accepts
an Android {@link android.content.Context} instance as its parameter. A
Context is a handle to the system; it provides services like
resolving resources, obtaining access to databases and preferences, and so
on. The Activity class inherits from Context, and because your
HelloAndroid class is a subclass of Activity, it is also a Context. So, you can
pass this
as your Context reference to the TextView.
Next, define the text content with {@link android.widget.TextView setText(CharSequence) setText()}.
Finally, pass the TextView to {@link android.app.Activity#setContentView(View) setContentView()} in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen.
There it is — "Hello, World" in Android! The next step, of course, is to see it running.
The Eclipse plugin makes it very easy to run your applications. Select Run > Run Configurations (in Eclipse 3.3, Run > Open Run Dialog).
Select the "Android Application" entry, and click the icon in the top left corner (the one depicting a sheet of paper with a plus symbol) or double-click on "Android Application." You should have a new launcher entry named "New_configuration".
Change the name to something meaningful like "Android Activity." Then pick click the Browse button and select your HelloAndroid project. The plugin will automatically scan your project for Activity subclasses and add each one it finds to the drop-down list under "Launch Action." Because the HelloAndroid project only has one Activity, it will be the default Activity. Leave "Launch Default Activity" selected.
Click the Apply, then Run. The Android Emulator will start and once it's booted up your application will appear. You should now see something like this:
The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in the /res/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object.
That covers the basic "Hello World" tutorial, but you should continue reading for some more valuable information about developing Android applications.
The "Hello, World" example you just completed uses what is called a "programmatic" UI layout. This means that you constructed and built your application's UI directly in source code. If you've done much UI programming, you're probably familiar with how brittle that approach can sometimes be: small changes in layout can result in big source-code headaches. It's also very easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code.
That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to show an example. Here's an XML layout file that is identical in behavior to the programmatically-constructed example:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/>
The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, however, is just one View element). You can use the name of any class that extends {@link android.view.View} as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it very easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout. This model is inspired by the web development model, wherein you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data.
In the above XML example, there's just one View element: the TextView
,
which has four XML attributes. Here's a summary of what they mean:
Attribute | Meaning |
---|---|
xmlns:android
|
This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. |
android:layout_width
|
This attribute defines how much of the available width on the screen this View should consume.
In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means. |
android:layout_height
|
This is just like android:layout_width, except that it refers to available screen height. |
android:text
|
This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file. For more information, see Resources and Internationalization. |
These XML layout files belong in the res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code assets that your application requires. In addition to layout files, resources also include assets such as images, sounds, and localized strings.
When you want a different design for landscape, put your layout XML file inside /res/layout-land. Android will automatically look here when the layout changes. Without this special landscape layout defined, Android will stretch the default layout.
The Eclipse plugin automatically creates one of these layout files for you: main.xml. In the "Hello World" application you just completed, this file was ignored and you created a layout programmatically. This was meant to teach you more about the Android framework, but you should almost always define your layout in an XML file instead of in your code. The following procedures will instruct you how to change your existing application to use an XML layout.
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/>
Save the file.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello, Android! I am a string resource!</string> <string name="app_name">Hello, Android</string> </resources>
HelloAndroid
class use the
XML layout. Edit the file to look like this:
package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
When you make this change, type it by hand to try the code-completion feature. As you begin typing "R.layout.main" the plugin will offer you suggestions. You'll find that it helps in a lot of situations.
Instead of passing setContentView()
a View object, you give it a reference
to the layout resource.
The resource is identified as R.layout.main
, which is actually a compiled object representation of
the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for
you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you
when you run Ant to build the application. (More about the R class in a moment.)
Now re-run your application — because you've created a launch configuration, all you need to do is click the green arrow icon to run, or select Run > Run History > Android Activity. Other than the change to the TextView string, the application looks the same. After all, the point was to show that the two different layout approaches produce identical results.
Tip: Use the shortcut Ctrl-F11 (Cmd-Shift-F11, on Mac) to run your currently visible application.
Continue reading for an introduction to debugging and a little more information on using other IDEs. When you're ready to learn more, read Application Fundamentals for an introduction to all the elements that make Android applications work. Also refer to the Developer's Guide introduction page for an overview of the Dev Guide documentation.
In Eclipse, open the file named R.java (in the /gen [Generated Java Files] folder). It should look something like this:
package com.example.helloandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }
A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for.
It's possible yours looks slighly different than this (perhaps the hexadecimal values are different). For now, notice the inner class named "layout", and its member field "main". The Eclipse plugin noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (such as strings in the res/values/string.xml file or drawables inside the res/drawable/ direcory) you'll see R.java change to keep up.
When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).
You should never edit this file by hand.
The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid source code to look like this:
package com.android.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object o = null; o.toString(); setContentView(R.layout.main); } }
This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:
Press "Force Quit" to terminate the application and close the emulator window.
To find out more about the error, set a breakpoint in your source code
on the line Object o = null;
(double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello,
Android from the menu to enter debug mode. Your app will restart in the
emulator, but this time it will suspend when it reaches the breakpoint you
set. You can then step through the code in Eclipse's Debug Perspective,
just as you would for any other application.
If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't worry though — you don't lose any functionality just because you don't use Eclipse.
The Android Plugin for Eclipse is really just a wrapper around a set of tools included with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, and others are documented elsewhere.) Thus, it's possible to wrap those tools with another tool, such as an 'ant' build file.
The Android SDK includes a toolk named "android" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatible build.xml file. This allows you to build your project from the command line, or integrate it with the IDE of your choice.
For example, to create a HelloAndroid project similar to the one created in Eclipse, use this command:
android create project \ --package com.android.helloandroid \ --activity HelloAndroid \ --target 1 \ --path <path-for-your-project>/HelloAndroid \ --mode activity
This creates the required folders and files for the project at the location defined by the path.
To build the project, you'd then run the command ant
. When that command
successfully completes, you'll be left with a file named HelloAndroid.apk under
the "bi"' directory. That .apk file is an Android Package, and can be
installed and run in your emulator using the 'adb' tool.
For more information on how to use these tools, please read Developing in Other IDEs.