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