1page.title=Hello, World 2parent.title=Tutorials 3parent.link=../browser.html?tag=tutorial 4@jd:body 5<div id="qv-wrapper"> 6<div id="qv"> 7 <h2>In this document</h2> 8 <ol> 9 <li><a href="#platform">Install a Platform</a></li> 10 <li><a href="#avd">Create an AVD</a></li> 11 <li><a href="#create">Create the Project</a></li> 12 <li><a href="#ui">Construct the UI</a></li> 13 <li><a href="#run">Run the Code</a></li> 14 <li><a href="#upgrading">Upgrade the UI to an XML Layout</a></li> 15 <li><a href="#debugging">Debug Your Project</a></li> 16 <li><a href="#noeclipse">Creating the Project Without Eclipse</a></li> 17 </ol> 18 </div> 19</div> 20 21<p>As a developer, you know that the first impression of a development framework is how easy it is 22to write "Hello, World." Well, on Android, it's pretty easy. It's particularly easy if you're using 23Eclipse as your IDE, because we've provided a great plugin that handles your project creation and 24management to greatly speed up your development cycles.</p> 25 26<p>This tutorial assumes that you're using Eclipse. If you're using the command line, see 27<a href="{@docRoot}/guide/developing/building/building-cmdline.html">Building and Running from the 28Command Line</a>. You can then return to this tutorial and ignore anything about Eclipse.</p> 29 30<p>Before you start, you should already have the SDK installed, and if you're 31using Eclipse, you should have installed the ADT plugin as well. If you have not 32installed these, see <a href="{@docRoot}sdk/installing.html">Installing the 33Android SDK</a> and return here when you've completed the installation.</p> 34 35<h2 id="platform">Install a Platform</h2> 36 37<p>To run the Hello World application, you need to install at least one Android 38platform in your SDK environment. If you have not already performed this step, 39you need to do it now.</p> 40 41<p>To install a platform in Eclipse:</p> 42 43<ol> 44 45 <li>In the Android SDK and AVD Manager, choose <strong>Available 46Packages</strong> in the left panel.</li> 47 48<li>In the right panel, expand the Android Repository list to display 49the components available for installation.</li> 50 51 <li>Select at least one platform to install, and click <strong>Install 52Selected</strong>. If you aren't sure which platform to install, use the latest 53version.</li> 54</ol> 55 56<h2 id="avd">Create an AVD</h2> 57 58<div class="sidebox-wrapper"> 59 <div class="sidebox"> 60 <p>To learn more about how to use AVDs and the options 61 available to you, see <a href="{@docRoot}guide/developing/devices/index.html">Managing 62 Virtual Devices</a>.</p> 63 </div> 64</div> 65 66<p>In this tutorial, you will run your application in the Android Emulator. 67Before you can launch the emulator, you must create an 68Android Virtual Device (AVD). An AVD defines the system image and 69device settings used by the emulator.</p> 70 71 72 73<p>To create an AVD:</p> 74<ol> 75 <li>In Eclipse, select <strong>Window > Android SDK and AVD Manager</strong>.</li> 76 <li>Select <strong>Virtual Devices</strong> in the left panel.</li> 77 78 <li>Click <strong>New...</strong>. 79 <p>The <strong>Create New AVD</strong> dialog appears.</p> 80 </li> 81 <li>Type the name of the AVD, such as "my_avd".</li> 82 <li>Choose a target. 83 <p>The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want 84 to run on the emulator. For this tutorial, choose the latest platform that you have installed 85 and ignore the rest of the fields.</p> 86 </li> 87 <li>Click <strong>Create AVD</strong>.</li> 88</ol> 89<h2 id="create">Create a New Android Project</h2> 90 91<p>After you've created an AVD you can move to the next step and start a new Android project in 92Eclipse.</p> 93 94<ol> 95 <li>In Eclipse, select <strong>File > New > Project...</strong>. 96 <p>If the ADT 97 Plugin for Eclipse has been successfully installed, the resulting dialog 98 should have a folder labeled "Android" which should contain 99 "Android Project". (After you create one or more Android projects, an entry for 100 "Android XML File" will also be available.)</p> 101 </li> 102 103 <li>Select "Android Project" and click <strong>Next</strong>.<br/> 104 <a href="images/hello_world_0.png"><img src="images/hello_world_0.png" style="height:230px" alt="" /></a> 105 </li> 106 107 <li>Fill in the project details with the following values: 108 <ul> 109 <li><em>Project name:</em> HelloAndroid</li> 110 <li><em>Build Target:</em> Select a platform version that is equal to or lower than the 111 target you chose for your AVD.</li> 112 <li><em>Application name:</em> Hello, Android</li> 113 <li><em>Package name:</em> com.example.helloandroid (or your own private namespace)</li> 114 <li><em>Create Activity:</em> HelloAndroid</li> 115 </ul> 116 <p>Click <strong>Finish</strong>.</p> 117 118 <a href="images/hello_world_1.png"><img src="images/hello_world_1.png" style="height:400px" alt="" /></a> 119 120 <p>Here is a description of each field:</p> 121 122 <dl> 123 <dt><em>Project Name</em></dt> 124 <dd>This is the Eclipse project name — the name of the directory 125 that contains the project files.</dd> 126 <dt><em>Build Target</em></dt> 127 <dd>This is the version of the Android SDK that you're using to build your 128 application. For example, if you choose Android 2.1, your application will be 129 compiled against the Android 2.1 platform library. The target you choose here 130 does not have to match the target you chose for your AVD; however, the target must 131 be equal to or lower than the target you chose for your AVD. Android 132 applications are forward-compatible, which means an application will run on the 133 platform against which it is built as well as all platforms that are released in the 134 future. For example, an application that is built against the 2.1 platform library 135 will run normally on an AVD or device that is running the 2.3.3. The reverse is not 136 true.</dd> 137 <dt><em>Application Name</em></dt> 138 <dd>This is the human-readable title for your application — the name that 139 appears on the Android device.</dd> 140 <dt><em>Package Name</em></dt> 141 <dd>This is the package namespace (following the same rules as for 142 packages in the Java programming language) that you want all your source code to 143 reside under. This also sets the package name under which the stub 144 Activity is generated. 145 <p>Your package name must be unique across 146 all packages installed on the Android system; for this reason, it's 147 important to use a standard domain-style package for your 148 applications. The example above uses the "com.example" namespace, which is 149 a namespace reserved for example documentation — 150 when you develop your own applications, you should use a namespace that's 151 appropriate to your organization or entity.</p></dd> 152 <dt><em>Create Activity</em></dt> 153 <dd>This is the name for the class stub that is generated by the plugin. 154 This is a subclass of Android's {@link android.app.Activity} class. An 155 Activity is simply a class that can run and do work. It can create a UI if it 156 chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an 157 Activity is almost always used as the basis for an application.</dd> 158 <dt><em>Min SDK Version</em></dt> 159 <dd>This value specifies the minimum API Level on which your application will run. 160 The <em>Min SDK Version</em> should be the same as the <em>Build Target</em> you 161 chose. For example, if the <em>Build Target</em> is Android 2.1, then the <em>Min 162 SDK Version</em> should be 7 or lower (it can never be higher than 7). For more 163 information, see 164 <a href="{@docRoot}guide/appendix/api-levels.html">Android API Levels</a>. 165 </dd> 166 </dl> 167 168 <p><em>Other fields</em>: The checkbox for "Use default location" allows you to change 169 the location on disk where the project's files are generated and stored.</p> 170 </li> 171</ol> 172 173<p>Your Android project is now ready. It should be visible in the Package Explorer on the left. Open 174the <code>HelloAndroid.java</code> file, located inside <em>HelloAndroid > src > 175com.example.helloandroid</em>). It should look like this:</p> 176 177<pre> 178package com.example.helloandroid; 179 180import android.app.Activity; 181import android.os.Bundle; 182 183public class HelloAndroid extends Activity { 184 /** Called when the activity is first created. */ 185 @Override 186 public void onCreate(Bundle savedInstanceState) { 187 super.onCreate(savedInstanceState); 188 setContentView(R.layout.main); 189 } 190}</pre> 191 192<p>Notice that the class is based on the {@link android.app.Activity} class. An Activity is a 193single application entity that is used to perform actions. An application may have many separate 194activities, but the user interacts with them one at a time. The 195{@link android.app.Activity#onCreate(Bundle) onCreate()} method 196is called by the Android system when your Activity starts — 197it is where you should perform all initialization and UI setup. An activity is not required to 198have a user interface, but usually does.</p> 199 200<p>Now let's modify some code! </p> 201 202 203<h2 id="ui">Construct the UI</h2> 204 205<p>Take a look at the revised code below and then make the same changes to your HelloAndroid class. 206The bold items are lines that have been added.</p> 207 208<pre> 209package com.example.helloandroid; 210 211import android.app.Activity; 212import android.os.Bundle; 213<strong>import android.widget.TextView;</strong> 214 215public class HelloAndroid extends Activity { 216 /** Called when the activity is first created. */ 217 @Override 218 public void onCreate(Bundle savedInstanceState) { 219 super.onCreate(savedInstanceState); 220 <strong>TextView tv = new TextView(this); 221 tv.setText("Hello, Android"); 222 setContentView(tv);</strong> 223 } 224}</pre> 225 226<p class="note"><strong>Tip:</strong> An easy way to add import packages to your project is 227to press <strong>Ctrl-Shift-O</strong> (<strong>Cmd-Shift-O</strong>, on Mac). This is an Eclipse 228shortcut that identifies missing packages based on your code and adds them for you. You may have 229to expand the <code>import</code> statements in your code for this to work.</p> 230 231<p>An Android user interface is composed of hierarchies of objects called 232Views. A {@link android.view.View} is a drawable object used as an element in your UI layout, 233such as a button, image, or (in this case) a text label. Each of these objects is a subclass 234of the View class and the subclass that handles text is {@link android.widget.TextView}.</p> 235 236<p>In this change, you create a TextView with the class constructor, which accepts 237an Android {@link android.content.Context} instance as its parameter. A 238Context is a handle to the system; it provides services like 239resolving resources, obtaining access to databases and preferences, and so 240on. The Activity class inherits from Context, and because your 241HelloAndroid class is a subclass of Activity, it is also a Context. So, you can 242pass <code>this</code> as your Context reference to the TextView.</p> 243 244<p>Next, you define the text content with 245{@link android.widget.TextView#setText(CharSequence) setText()}.</p> 246 247<p>Finally, you pass the TextView to 248{@link android.app.Activity#setContentView(View) setContentView()} in order to 249display it as the content for the Activity UI. If your Activity doesn't 250call this method, then no UI is present and the system will display a blank 251screen.</p> 252 253<p>There it is — "Hello, World" in Android! The next step, of course, is 254to see it running.</p> 255 256 257<h2 id="run">Run the Application</h2> 258 259<p>The Eclipse plugin makes it easy to run your applications:</p> 260 261<ol> 262 <li>Select <strong>Run > Run</strong>.</li> 263 <li>Select "Android Application".</li> 264</ol> 265 266<div class="sidebox-wrapper"> 267 <div class="sidebox"> 268 <p>To learn more about creating and editing run configurations in Eclipse, refer to 269 <a href="{@docRoot}guide/developing/eclipse-adt.html#RunConfig">Developing In Eclipse, 270 with ADT</a>.</p> 271 </div> 272</div> 273 274<p>The Eclipse plugin automatically creates a new run configuration for your project 275and then launches the Android Emulator. Depending on your environment, the Android 276emulator might take several minutes to boot fully, so please be patient. When the 277emulator is booted, the Eclipse plugin installs your application 278and launches the default Activity. You should now see something like this:</p> 279 280 <a href="images/hello_world_5.png"><img src="images/hello_world_5.png" style="height:230px" alt="" /></a> 281 282<p>The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin 283creates this automatically (the string is defined in the <code>res/values/strings.xml</code> file and referenced 284by your <code>AndroidManifest.xml</code> file). The text below the title is the actual text that you have 285created in the TextView object.</p> 286 287<p>That concludes the basic "Hello World" tutorial, but you should continue reading for some more 288valuable information about developing Android applications.</p> 289 290 291<h2 id="upgrading">Upgrade the UI to an XML Layout</h2> 292 293<p>The "Hello, World" example you just completed uses what is called a "programmatic" 294UI layout. This means that you constructed and built your application's UI 295directly in source code. If you've done much UI programming, you're 296probably familiar with how brittle that approach can sometimes be: small 297changes in layout can result in big source-code headaches. It's also 298easy to forget to properly connect Views together, which can result in errors in 299your layout and wasted time debugging your code.</p> 300 301<p>That's why Android provides an alternate UI construction model: XML-based 302layout files. The easiest way to explain this concept is to show an 303example. Here's an XML layout file that is identical in behavior to the 304programmatically-constructed example:</p> 305 306<pre><?xml version="1.0" encoding="utf-8"?> 307<TextView xmlns:android="http://schemas.android.com/apk/res/android" 308 android:id="@+id/textview" 309 android:layout_width="fill_parent" 310 android:layout_height="fill_parent" 311 android:text="@string/hello"/></pre> 312 313<p>The general structure of an Android XML layout file is simple: it's a tree 314of XML elements, wherein each node is the name of a View class 315(this example, however, is just one View element). You can use the 316name of any class that extends {@link android.view.View} as an element in your XML layouts, 317including custom View classes you define in your own code. This 318structure makes it easy to quickly build up UIs, using a more simple 319structure and syntax than you would use in a programmatic layout. This model is inspired 320by the web development model, wherein you can separate the presentation of your 321application (its UI) from the application logic used to fetch and fill in data.</p> 322 323<p>In the above XML example, there's just one View element: the <code>TextView</code>, 324which has five XML attributes. Here's a summary of what they mean:</p> 325 326<table> 327 <tbody> 328 <tr> 329 <th> 330 Attribute 331 </th> 332 <th> 333 Meaning 334 </th> 335 </tr> 336 <tr> 337 <td> 338 <code>xmlns:android</code> 339 </td> 340 <td> 341 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> 342 </td> 343 </tr> 344 <tr> 345 <td> 346 <code>android:id</code> 347 </td> 348 <td> 349 This attribute assigns a unique identifier to the <code>TextView</code> element. 350 You can use the assigned ID to reference this View from your source code or from other 351 XML resource declarations. 352 </td> 353 </tr> 354 <tr> 355 <td> 356 <code>android:layout_width</code> 357 </td> 358 <td> 359 This attribute defines how much of the available width on the screen this View should consume. 360 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.<br> 361 </td> 362 </tr> 363 <tr> 364 <td> 365 <code>android:layout_height</code> 366 </td> 367 <td> 368 This is just like android:layout_width, except that it refers to available screen height. 369 </td> 370 </tr> 371 <tr> 372 <td> 373 <code>android:text</code> 374 </td> 375 <td> 376 This sets the text that the TextView should display. In this example, you use a string 377 resource instead of a hard-coded string value. 378 The <em>hello</em> string is defined in the <em>res/values/strings.xml</em> file. This is the 379 recommended practice for inserting strings to your application, because it makes the localization 380 of your application to other languages graceful, without need to hard-code changes to the layout file. 381 For more information, see <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources 382 and Internationalization</a>. 383 </td> 384 </tr> 385 </tbody> 386</table> 387 388 389<p>These XML layout files belong in the <code>res/layout/</code> directory of your project. The "res" is 390short for "resources" and the directory contains all the non-code assets that 391your application requires. In addition to layout files, resources also include assets 392such as images, sounds, and localized strings.</p> 393 394<div class="sidebox-wrapper"> 395<div class="sidebox"> 396 <h2>Landscape layout</h2> 397 <p>When you want a different design for landscape, put your layout XML file 398 inside /res/layout-land. Android will automatically look here when the layout changes. 399 Without this special landscape layout defined, Android will stretch the default layout.</p> 400</div> 401</div> 402 403<p>The Eclipse plugin automatically creates one of these layout files for you: main.xml. 404In the "Hello World" application you just completed, this file was ignored and you created a 405layout programmatically. This was meant to teach you more 406about the Android framework, but you should almost always define your layout 407in an XML file instead of in your code. 408The following procedures will instruct you how to change your 409existing application to use an XML layout.</p> 410 411<ol> 412 <li>In the Eclipse Package Explorer, expand the 413<code>/res/layout/</code> folder and open <code>main.xml</code> (once opened, you might need to click 414the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with 415the following XML: 416 417<pre><?xml version="1.0" encoding="utf-8"?> 418<TextView xmlns:android="http://schemas.android.com/apk/res/android" 419 android:id="@+id/textview" 420 android:layout_width="fill_parent" 421 android:layout_height="fill_parent" 422 android:text="@string/hello"/></pre> 423<p>Save the file.</p> 424</li> 425 426<li>Inside the <code>res/values/</code> folder, open <code>strings.xml</code>. 427This is where you should save all default text strings for your user interface. If you're using Eclipse, then 428ADT will have started you with two strings, <em>hello</em> and <em>app_name</em>. 429Revise <em>hello</em> to something else. Perhaps "Hello, Android! I am a string resource!" 430The entire file should now look like this: 431<pre> 432<?xml version="1.0" encoding="utf-8"?> 433<resources> 434 <string name="hello">Hello, Android! I am a string resource!</string> 435 <string name="app_name">Hello, Android</string> 436</resources> 437</pre> 438</li> 439 440<li>Now open and modify your <code>HelloAndroid</code> class and use the 441XML layout. Edit the file to look like this: 442<pre> 443package com.example.helloandroid; 444 445import android.app.Activity; 446import android.os.Bundle; 447 448public class HelloAndroid extends Activity { 449 /** Called when the activity is first created. */ 450 @Override 451 public void onCreate(Bundle savedInstanceState) { 452 super.onCreate(savedInstanceState); 453 setContentView(R.layout.main); 454 } 455}</pre> 456 457<p>When you make this change, type it by hand to try the 458code-completion feature. As you begin typing "R.layout.main" the plugin will offer you 459suggestions. You'll find that it helps in a lot of situations.</p> 460 461<p>Instead of passing <code>setContentView()</code> a View object, you give it a reference 462to the layout resource. 463The resource is identified as <code>R.layout.main</code>, which is actually a compiled object representation of 464the layout defined in <code>/res/layout/main.xml</code>. The Eclipse plugin automatically creates this reference for 465you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you 466when you run Ant to build the application. (More about the R class in a moment.)</p> 467</li> 468</ol> 469 470<p>Now re-run your application — because you've created a launch configuration, all 471you need to do is click the green arrow icon to run, or select 472<strong>Run > Run History > Android Activity</strong>. Other than the change to the TextView 473string, the application looks the same. After all, the point was to show that the two different 474layout approaches produce identical results.</p> 475 476<p class="note"><strong>Note:</strong> You may have to unlock the screen on the emulator to see 477your application — just as you would unlock the screen on a device. If you have problems 478running the emulator, see <a href="{@docRoot}guide/developing/devices/emulator.html">Using the 479Android Emulator</a>.</p> 480 481<p>Continue reading for an introduction 482to debugging and a little more information on using other IDEs. When you're ready to learn more, 483read <a href="{@docRoot}guide/topics/fundamentals.html">Application 484Fundamentals</a> for an introduction to all the elements that make Android applications work. 485Also refer to the <a href="{@docRoot}guide/index.html">Developer's Guide</a> 486introduction page for an overview of the <em>Dev Guide</em> documentation.</p> 487 488 489<div class="special"> 490<h3>R class</h3> 491<p>In Eclipse, open the file named <code>R.java</code> (in the <code>gen/</code> [Generated Java Files] folder). 492It should look something like this:</p> 493 494<pre> 495package com.example.helloandroid; 496 497public final class R { 498 public static final class attr { 499 } 500 public static final class drawable { 501 public static final int icon=0x7f020000; 502 } 503 public static final class id { 504 public static final int textview=0x7f050000; 505 } 506 public static final class layout { 507 public static final int main=0x7f030000; 508 } 509 public static final class string { 510 public static final int app_name=0x7f040001; 511 public static final int hello=0x7f040000; 512 } 513} 514</pre> 515 516<p>A project's <code>R.java</code> file is an index into all the resources defined in the 517file. You use this class in your source code as a sort of short-hand 518way to refer to resources you've included in your project. This is 519particularly powerful with the code-completion features of IDEs like Eclipse 520because it lets you quickly and interactively locate the specific reference 521you're looking for.</p> 522 523<p>It's possible yours looks slightly different than this (perhaps the hexadecimal values are 524different). 525For now, notice the inner class named "layout", and its 526member field "main". The Eclipse plugin noticed the XML 527layout file named main.xml and generated a class for it here. As you add other 528resources to your project (such as strings in the <code>res/values/string.xml</code> file or drawables inside 529the <code>res/drawable/</code> directory) you'll see <code>R.java</code> change to keep up.</p> 530<p>When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).</p> 531<p><em>You should never edit this file by hand.</em></p> 532</div> 533 534<h2 id="debugging">Debug Your Project</h2> 535 536<p>The Android Plugin for Eclipse also has excellent integration with the Eclipse 537debugger. To demonstrate this, introduce a bug into 538your code. Change your HelloAndroid source code to look like this:</p> 539 540<pre> 541package com.example.helloandroid; 542 543import android.app.Activity; 544import android.os.Bundle; 545 546public class HelloAndroid extends Activity { 547 /** Called when the activity is first created. */ 548 @Override 549 public void onCreate(Bundle savedInstanceState) { 550 super.onCreate(savedInstanceState); 551 Object o = null; 552 o.toString(); 553 setContentView(R.layout.main); 554 } 555}</pre> 556 557<p>This change simply introduces a NullPointerException into your code. If 558you run your application again, you'll eventually see this:</p> 559 560 <a href="images/hello_world_8.png"><img src="images/hello_world_8.png" style="height:230px" alt="" /></a> 561 562<p>Press "Force Quit" to terminate the application and close the emulator window.</p> 563 564<p>To find out more about the error, set a breakpoint in your source code 565on the line <code>Object o = null;</code> (double-click on the marker bar next to the source code line). Then select <strong>Run > Debug History > Hello, 566Android</strong> from the menu to enter debug mode. Your app will restart in the 567emulator, but this time it will suspend when it reaches the breakpoint you 568set. You can then step through the code in Eclipse's Debug Perspective, 569just as you would for any other application.</p> 570 571 <a href="images/hello_world_9.png"><img src="images/hello_world_9.png" style="height:230px" alt="" /></a> 572 573 574<h2 id="noeclipse">Creating the Project without Eclipse</h2> 575 576 <p>If you don't use Eclipse (such as if you prefer another IDE, or simply use text 577 editors and command line tools) then the Eclipse plugin can't help you. 578 Don't worry though — you don't lose any functionality just because you don't 579 use Eclipse.</p> 580 581 <p>The Android Plugin for Eclipse is really just a wrapper around a set of tools 582 included with the Android SDK. (These tools, like the emulator, aapt, adb, 583 ddms, and others are <a href="{@docRoot}guide/developing/tools/index.html">documented elsewhere.</a>) 584 Thus, it's possible to 585 wrap those tools with another tool, such as an 'ant' build file.</p> 586 587 <p>The Android SDK includes a tool named "android" that can be 588 used to create all the source code and directory stubs for your project, as well 589 as an ant-compatible <code>build.xml</code> file. This allows you to build your project 590 from the command line, or integrate it with the IDE of your choice.</p> 591 592 <p>For example, to create a HelloAndroid project similar to the one created 593 in Eclipse, use this command:</p> 594 595 <pre> 596android create project \ 597 --package com.example.helloandroid \ 598 --activity HelloAndroid \ 599 --target 2 \ 600 --path <em><path-to-your-project></em>/HelloAndroid 601</pre> 602 603 <p>This creates the required folders and files for the project at the location 604 defined by the <em>path</em>.</p> 605 606 <p>For more information on how to use the SDK tools to create and build projects, please read 607<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p>