blob: c37d6f95e5f5edcfc869e0b236be7af7434f34e7 [file] [log] [blame]
page.title=Hello, Android!
@jd:body
<p>First impressions matter, and as a developer you know that the first impression
you get of a development framework is how easy it is to write "Hello,
World!" Well, in Android, it's pretty easy. Here's how it looks:</p>
<ul>
<li><a href="#create">Create the Project</a></li>
<li><a href="#ui">Construct the UI</a></li>
<li><a href="#run">Run the Code: Hello, Android</a></li>
</ul>
<p>The sections below spell it all out in detail. </p>
<ul>
<li><a href="#upgrading">Upgrading the UI to an XML Layout</a> </li>
<li><a href="#debugging">Debugging Your Project</a> </li>
<li><a href="#noeclipse">Creating a Project without Eclipse</a> </li>
</ul>
<p>Let's jump in!</p>
<a name="create"></a>
<h2>Create the Project </h2>
<p>Creating the project is as simple as can be. An Eclipse
plugin is available making Android development a snap. </p>
<p>You'll need to have a development computer with the Eclipse IDE installed (see <a
href="{@docRoot}intro/installing.html#developmentrequirements">System and Software Requirements</a>), and
you'll need to install the <a
href="{@docRoot}intro/installing.html#installingplugin">Android Eclipse Plugin (ADT)</a>. Once you have those ready, come back here. </p>
<p>First, here's a high-level summary of how to build "Hello, World!":</p>
<ol>
<li>
Create a new "Android Project" via the <strong>File &gt; New &gt; Project</strong> menu.
</li>
<li>
Fill out the project details in the New Android Project dialog.
</li>
<li>
Edit the auto-generated source code template to display some output.
</li>
</ol>
<p> That's it! Next, let's go through each step above in detail. </p>
<ol class="listhead">
<li>Create a new Android Project
<p>From Eclipse, select the <strong>File &gt; New &gt; Project</strong> 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".</p>
<p><img src="{@docRoot}images/hello_world_0.png"/></p>
<p>Once you've selected "Android Project", click the Next button.</p>
</li>
<li>Fill out the project details
<p>The next screen allows you to enter the relevant details for your project.
Here's an example:</p>
<p><img src="{@docRoot}images/hello_world_1.png"/></p>
<p>Here's what each field on this screen means:</p>
<table>
<tbody>
<tr>
<td>Project Name </td>
<td>This is the name of the directory or folder on your computer that you
want to contain the project.</td>
</tr>
<tr>
<td>Package Name </td>
<td>This is the package namespace (following the same rules as for
packages in the Java programming language) that you want all your source code to
reside under. This also sets the package name under which the stub
Activity will be generated.<p/>
The package name you use in your application must be unique across
all packages installed on the system; for this reason, it's very
important to use a standard domain-style package for your
applications. In the example above, we used the
package domain "com.android"; you should use a
different one appropriate to your organization.</td>
</tr>
<tr>
<td>Activity Name </td>
<td>This is the name for the class stub that will be generated by the plugin.
This will be a subclass of Android's Activity class. An Activity is simply a
class that can run and do work. It can create a UI if it chooses, but it
doesn't need to. </td>
</tr>
<tr>
<td> Application Name </td>
<td> This is the human-readable title for your application. </td>
</tr>
</tbody>
</table>
<p>The checkbox for toggling "Use default location" allows you to change the
location on disk where the project's files will be generated and stored.</p>
</li>
<li>Edit the auto-generated source code
<p>After the plugin runs, you'll have a class named HelloAndroid
(found in your package, HelloAndroid > src > com.android.hello). It should look like
this:</p>
<pre>public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
&#64;Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}</pre>
<p>Now, you <em>could</em> run this right away, but let's go a little further,
so we understand more about what's happening.
So, the next step is to modify some code! </p>
</li>
</ol>
<a name="ui"></a>
<h2>Construct the UI</h2>
<p>Take a look at this revised code, below, and make the same changes to your HelloAndroid.java file. We'll dissect
it line by line:</p>
<pre>
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
&#64;Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText(&quot;Hello, Android&quot;);
setContentView(tv);
}
}</pre>
<p class="note"><strong>Tip:</strong> If you forgot to import the TextView package, try this:
press <strong>Ctrl-Shift-O</strong> (<strong>Cmd-Shift-O</strong>, on Mac). This is an Eclipse
shortcut to organize imports&mdash;it identifies missing packages and adds them for you.</p>
<p>In Android, user interfaces are composed of hierarchies of classes called
Views. A View is simply a drawable object, such as a radio button, an
animation, or (in our case) a text label. The specific name for the View
subclass that handles text is simply TextView.</p>
<p>Here's how you construct a TextView:</p>
<pre>TextView tv = new TextView(this);</pre>
<p>The argument to TextView's constructor is an Android Context instance. The
Context is simply 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. Since our
HelloAndroid class is a subclass of Activity, it is also a Context, and so we can
pass the <code>this</code> reference to the TextView.</p>
<p>Once we've constructed the TextView, we need to tell it what to display:</p>
<pre>tv.setText(&quot;Hello, Android&quot;);</pre>
<p>Nothing too surprising there.</p>
<p>At this point, we've constructed a TextView and told it what text to
display. The final step is to connect this TextView with the on-screen
display, like so:</p>
<pre>setContentView(tv);</pre>
<p>The <code>setContentView()</code> method on Activity indicates to the system which
View should be associated with the Activity's UI. If an Activity doesn't
call this method, no UI is present at all and the system will display a blank
screen. For our purposes, all we want is to display some text, so we pass it
the TextView we just created.</p>
<p>There it is &mdash; "Hello, World" in Android! The next step, of course, is
to see it running.</p>
<a name="run"></a>
<h2>Run the Code: Hello, Android</h2>
<p>The Eclipse plugin makes it very easy to run your applications. Begin by
selecting the <strong>Run &gt; Open Run Dialog</strong> menu entry (in Eclipse 3.4, it's
<strong>Run > Run Configurations</strong>). You should see a dialog
like this:</p>
<div id="o.:l" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_2.png"/>
</div>
<p>Next, highlight the "Android Application" entry, and then click the icon in the
top left corner (the one depicting a sheet of paper with a plus sign in the
corner) or simply double-click the "Android Application" entry. You should
have a new launcher entry named "New_configuration".</p>
<div id="z4_b" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_3.png"/>
</div>
<p>Change the name to something expressive, like "Hello, Android", and then pick
your project by clicking the Browse button. (If you have more than one
Android project open in Eclipse, be sure to pick the right one.) The
plugin will automatically scan your project for Activity subclasses, and add
each one it finds to the drop-down list under the "Activity:" label. Since
your "Hello, Android" project only has one, it will be the default, and you can
simply continue.</p>
<p>Click the "Apply" button. Here's an example:</p>
<div id="t66_" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_4.png"/>
</div>
<p>That's it &mdash; you're done! Click the Run button, and the Android Emulator
should start. Once it's booted up your application will appear. When all is said and done, you should
see something like this:</p>
<div id="qnhl" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_5.png"/>
</div>
<p>That's "Hello, World" in Android. Pretty straightforward, eh?
The next sections of the tutorial offer more detailed information that you may find valuable as you
learn more about Android.</p>
<a name="upgrading"></a>
<h2>Upgrading the UI to an XML Layout</h2>
<p>The "Hello, World" example you just completed uses what we call "programmatic"
UI layout. This means that you construct and build 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.</p>
<p>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 you just completed:</p>
<pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;fill_parent&quot;
android:text=&quot;Hello, Android&quot;/&gt;</pre>
<p>The general structure of an Android XML layout file is simple. It's a tree
of tags, where each tag is the name of a View class. In this example, it's
a very simple tree of one element, a TextView. You can use the
name of any class that extends View as a tag name 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 much simpler
structure and syntax than you would in source code. This model is inspired
by the web development model, where you can separate the presentation of your
application (its UI) from the application logic used to fetch and fill in data.</p>
<p>In this example, there are also four XML attributes. Here's a summary of what
they mean:</p>
<table>
<tbody>
<tr>
<th>
Attribute
</th>
<th>
Meaning
</th>
</tr>
<tr>
<td>
<code>xmlns:android</code>
</td>
<td>
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.<br>
</td>
</tr>
<tr>
<td>
<code>android:layout_width</code>
</td>
<td>
This attribute defines how much of the available width on the screen this View should consume. In this case, it's our only View so we want it to take up the entire screen, which is what a value of "fill_parent" means.<br>
</td>
</tr>
<tr>
<td>
<code>android:layout_height</code>
</td>
<td>
This is just like android:layout_width, except that it refers to available screen height.
</td>
</tr>
<tr>
<td>
<code>android:text</code>
</td>
<td>
This sets the text that the TextView should contain. In this example, it's our usual "Hello, Android" message.
</td>
</tr>
</tbody>
</table>
<p>So, that's what the XML layout looks like, but where do you put it? Under the /res/layout directory in your project. The "res" is
short for "resources" and that directory contains all the non-code assets that
your application requires. This includes things like images, localized
strings, and XML layout files.</p>
<p>The Eclipse plugin creates one of these XML files for you. In our example
above, we simply never used it. In the Package Explorer, expand the
folder /res/layout, and edit the file main.xml. Replace its contents with
the text above and save your changes.</p>
<p>Now open the file named R.java in your source code folder in the Package
Explorer. You'll see that it now looks something like this:</p>
<pre>
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=0x7f040000;
};
};
</pre>
<p>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.</p>
<p>The important thing to notice for now is the inner class named "layout", and its
member field "main". The Eclipse plugin noticed that you added a new XML
layout file and then regenerated this R.java file. As you add other
resources to your projects you'll see R.java change to keep up.</p>
<p>The last thing you need to do is modify your HelloAndroid source code to use the new
XML version of your UI, instead of the hard-coded version. Here's what
your new class will look like. As you can see, the source code becomes much
simpler:</p>
<pre>package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
&#64;Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}</pre>
<p>When you make this change, don't just copy-and-paste it in. Try out the code-completion feature on that R class. You'll probably find that it helps a lot.</p>
<p>Now that you've made this change, go ahead and re-run your application &mdash; all
you need to do is click the green Run arrow icon, or select
<strong>Run &gt; Run History &gt; Hello, Android</strong> from the menu. You should see.... well, exactly the same thing
you saw before! After all, the point was to show that the two different
layout approaches produce identical results.</p>
<p>There's a lot more to creating these XML layouts, but that's as far as we'll go
here. Read the <a
href="{@docRoot}devel/implementing-ui.html">Implementing a User Interface</a> documentation for more
information on the power of this approach.</p>
<a name="debugging"></a>
<h2>Debugging Your Project</h2>
<p>The Android Plugin for Eclipse also has excellent integration with the Eclipse
debugger. To demonstrate this, let's introduce a bug into
our code. Change your HelloAndroid source code to look like this:</p>
<pre>
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
&#64;Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Object o = null;
o.toString();
setContentView(R.layout.main);
}
}</pre>
<p>This change simply introduces a NullPointerException into your code. If
you run your application again, you'll eventually see this:</p>
<div id="go-9" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_8.png"/>
</div>
<p>Press "Force Quit" to terminate the application and close the emulator window.</p>
<p>To find out more about the error, set a breakpoint in your source code
on the line <code>Object o = null;</code> (double-click on the marker bar next to the source code line). Then select <strong>Run &gt; Debug History &gt; Hello,
Android</strong> 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.</p>
<div id="w2c9" style="PADDING:1em 0pt; TEXT-ALIGN:left">
<img src="{@docRoot}images/hello_world_9.png"/>
</div>
<a name="noeclipse"></a>
<h2>Creating the Project without Eclipse</h2>
<p>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 &mdash; you don't lose any functionality just because you don't
use Eclipse.</p>
<p>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 <a href="tools.html">documented elsewhere.</a>) Thus, it's possible to
wrap those tools with another tool, such as an 'ant' build file.</p>
<p>The Android SDK includes a Python script named "activitycreator.py" 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.</p>
<p>For example, to create a HelloAndroid project similar to the one we just created
via Eclipse, you'd use this command:</p>
<pre>activitycreator.py --out HelloAndroid com.android.hello.HelloAndroid</pre>
<p>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 'bin' directory. That .apk file is an Android Package, and can be
installed and run in your emulator using the 'adb' tool.</p>
<p>For more information on how to use these tools, please read the documentation
cited above.</p>