1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
|
page.title=Hello, World
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#platform">Install a Platform</a></li>
<li><a href="#avd">Create an AVD</a></li>
<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</a></li>
<li><a href="#upgrading">Upgrade the UI to an XML Layout</a></li>
<li><a href="#debugging">Debug Your Project</a></li>
<li><a href="#noeclipse">Creating the Project Without Eclipse</a></li>
</ol>
</div>
</div>
<p>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.</p>
<p>This tutorial assumes that you're using Eclipse. If you're not, see
<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.
You can then return to this tutorial and ignore anything about Eclipse.</p>
<p>Before you start, you should already have the SDK installed, and if you're
using Eclipse, you should have installed the ADT plugin as well. If you have not
installed these, see <a href="{@docRoot}sdk/installing.html">Installing the
Android SDK</a> and return here when you've completed the installation.</p>
<h2 id="platform">Install a Platform</h2>
<p>To run the Hello World application, you need to install at least one Android
platform in your SDK environment. If you have not already performed this step,
you need to do it now.</p>
<p>To install a platform in Eclipse:</p>
<ol>
<li>In the Android SDK and AVD Manager, choose <strong>Available
Packages</strong> in the left panel.</li>
<li>Click the repository site checkbox to display the components
available for installation.</li>
<li>Select at least one platform to install, and click <strong>Install
Selected</strong>. If you aren't sure which platform to install, use the latest
version.</li>
</ol>
<h2 id="avd">Create an AVD</h2>
<div class="sidebox-wrapper">
<div class="sidebox">
<p>To learn more about how to use AVDs and the options
available to you, refer to the
<a href="{@docRoot}guide/developing/tools/avd.html">Android
Virtual Devices</a> document.</p>
</div>
</div>
<p>In this tutorial, you will run your application 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.</p>
<p>To create an AVD:</p>
<ol>
<li>In Eclipse, choose <strong>Window > Android SDK and AVD Manager</strong>.
<li>Select <strong>Virtual Devices</strong> in the left panel.</li>
<li>Click <strong>New</strong>. </li>
<p>The <strong>Create New AVD</strong> dialog appears.</p>
<li>Type the name of the AVD, such as "my_avd".</li>
<li>Choose a target. The target is the platform (that is, the version of the Android
SDK, such as 2.1) you want to run on the emulator. </li>
<p>You can ignore the rest of the fields for now. </p>
<li>Click <strong>Create AVD</strong>.</li>
</ol>
<h2 id="create">Create a New Android Project</h2>
<p>After you've created an AVD, the next step is to start a new
Android project in Eclipse.</p>
<ol>
<li>From Eclipse, select <strong>File > New > Project</strong>.
<p>If the ADT
Plugin for Eclipse has been successfully installed, the resulting dialog
should have a folder labeled "Android" which should contain
"Android Project". (After you create one or more Android projects, an entry for
"Android XML File" will also be available.)</p>
</li>
<li>Select "Android Project" and click <strong>Next</strong>.<br/>
<a href="images/hello_world_0.png"><img src="images/hello_world_0.png" style="height:230px" alt="" /></a>
</li>
<li>Fill in the project details with the following values:
<ul>
<li><em>Project name:</em> HelloAndroid</li>
<li><em>Application name:</em> Hello, Android</li>
<li><em>Package name:</em> com.example.helloandroid (or your own private namespace)</li>
<li><em>Create Activity:</em> HelloAndroid</li>
</ul>
<p>Click <strong>Finish</strong>.</p>
<a href="images/hello_world_1.png"><img src="images/hello_world_1.png" style="height:230px" alt="" /></a>
<p>Here is a description of each field:</p>
<dl>
<dt><em>Project Name</em></dt>
<dd>This is the Eclipse Project name — the name of the directory
that will contain the project files.</dd>
<dt><em>Application Name</em></dt>
<dd>This is the human-readable title for your application — the name that
will appear on the Android device.</dd>
<dt><em>Package Name</em></dt>
<dd>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>Your package name must be unique across
all packages installed on the Android system; for this reason, it's
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.</p></dd>
<dt><em>Create Activity</em></dt>
<dd>This is the name for the class stub that will be generated by the plugin.
This will be a subclass of Android's {@link android.app.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. As the checkbox suggests, this is optional, but an
Activity is almost always used as the basis for an application.</dd>
<dt><em>Min SDK Version</em></dt>
<dd>This value specifies the minimum API Level required by your application. For
more information, see <a href="{@docRoot}guide/appendix/api-levels.html">Android API Levels</a>.
</dd>
</dl>
<p><em>Other fields</em>: The checkbox for "Use default location" allows you to change
the location on disk where the project's files will be generated and stored. "Build Target"
is the platform target that your application will be compiled against
(this should be selected automatically, based on your Min SDK Version).</p>
<p class="note">Notice that the "Build Target" you've selected uses the Android 1.1
platform. This means that your application will be compiled against the Android 1.1
platform library. If you recall, the AVD created above runs on the Android 1.5 platform.
These don't have to match; Android applications are forward-compatible, so an application
built against the 1.1 platform library will run normally on the 1.5 platform. The reverse
is not true.</p>
</li>
</ol>
<p>Your Android project is now ready. It should be visible in the Package
Explorer on the left.
Open the <code>HelloAndroid.java</code> file, located inside <em>HelloAndroid > src >
com.example.helloandroid</em>). It should look like this:</p>
<pre>
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);
}
}</pre>
<p>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.</p>
<p>Now let's modify some code! </p>
<h2 id="ui">Construct the UI</h2>
<p>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.</p>
<pre>
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
<strong>import android.widget.TextView;</strong>
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<strong>TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);</strong>
}
}</pre>
<p class="note"><strong>Tip:</strong> An easy way to add import packages to your project is
to press <strong>Ctrl-Shift-O</strong> (<strong>Cmd-Shift-O</strong>, on Mac). This is an Eclipse
shortcut that identifies missing packages based on your code and adds them for you.</p>
<p>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}.</p>
<p>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 <code>this</code> as your Context reference to the TextView.</p>
<p>Next, you define the text content with
{@link android.widget.TextView#setText(CharSequence) setText()}.</p>
<p>Finally, you 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.</p>
<p>There it is — "Hello, World" in Android! The next step, of course, is
to see it running.</p>
<h2 id="run">Run the Application</h2>
<p>The Eclipse plugin makes it easy to run your applications:</p>
<ol>
<li>Select <strong>Run > Run</strong>.</li>
<li>Select "Android Application".</li>
</ol>
<div class="sidebox-wrapper">
<div class="sidebox">
<p>To learn more about creating and editing run configurations in Eclipse, refer to
<a href="{@docRoot}guide/developing/eclipse-adt.html#RunConfig">Developing In Eclipse,
with ADT</a>.</p>
</div>
</div>
<p>The Eclipse ADT will automatically create a new run configuration for your project
and the Android Emulator will automatically launch. Once the emulator is booted up,
your application will appear after a moment. You should now see something like this:</p>
<a href="images/hello_world_5.png"><img src="images/hello_world_5.png" style="height:230px" alt="" /></a>
<p>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 <code>res/values/strings.xml</code> file and referenced
by your <code>AndroidManifest.xml</code> file). The text below the title is the actual text that you have
created in the TextView object.</p>
<p>That concludes the basic "Hello World" tutorial, but you should continue reading for some more
valuable information about developing Android applications.</p>
<h2 id="upgrading">Upgrade the UI to an XML Layout</h2>
<p>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
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:</p>
<pre><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id+/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"/></pre>
<p>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 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.</p>
<p>In the above XML example, there's just one View element: the <code>TextView</code>,
which has five 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:id</code>
</td>
<td>
This attribute assigns a unique identifier to the <code>TextView</code> element.
You can use the assigned ID to reference this View from your source code or from other
XML resource declarations.
</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 the only View so you 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 display. In this example, you use a string
resource instead of a hard-coded string value.
The <em>hello</em> string is defined in the <em>res/values/strings.xml</em> 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 <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources
and Internationalization</a>.
</td>
</tr>
</tbody>
</table>
<p>These XML layout files belong in the <code>res/layout/</code> 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.</p>
<div class="sidebox-wrapper">
<div class="sidebox">
<h2>Landscape layout</h2>
<p>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.</p>
</div>
</div>
<p>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.</p>
<ol>
<li>In the Eclipse Package Explorer, expand the
<code>/res/layout/</code> folder and open <code>main.xml</code> (once opened, you might need to click
the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with
the following XML:
<pre><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id+/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"/></pre>
<p>Save the file.</p>
</li>
<li>Inside the <code>res/values/</code> folder, open <code>strings.xml</code>.
This is where you should save all default text strings for your user interface. If you're using Eclipse, then
ADT will have started you with two strings, <em>hello</em> and <em>app_name</em>.
Revise <em>hello</em> to something else. Perhaps "Hello, Android! I am a string resource!"
The entire file should now look like this:
<pre>
<?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>
</pre>
</li>
<li>Now open and modify your <code>HelloAndroid</code> class use the
XML layout. Edit the file to look like this:
<pre>
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);
}
}</pre>
<p>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.</p>
<p>Instead of passing <code>setContentView()</code> a View object, you give it a reference
to the layout resource.
The resource is identified as <code>R.layout.main</code>, which is actually a compiled object representation of
the layout defined in <code>/res/layout/main.xml</code>. 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.)</p>
</li>
</ol>
<p>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
<strong>Run > Run History > Android Activity</strong>. 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.</p>
<p class="note"><strong>Tip:</strong> Use the shortcut <strong>Ctrl-F11</strong>
(<strong>Cmd-Shift-F11</strong>, on Mac) to run your currently visible application.</p>
<p>Continue reading for an introduction
to debugging and a little more information on using other IDEs. When you're ready to learn more,
read <a href="{@docRoot}guide/topics/fundamentals.html">Application
Fundamentals</a> for an introduction to all the elements that make Android applications work.
Also refer to the <a href="{@docRoot}guide/index.html">Developer's Guide</a>
introduction page for an overview of the <em>Dev Guide</em> documentation.</p>
<div class="special">
<h3>R class</h3>
<p>In Eclipse, open the file named <code>R.java</code> (in the <code>gen/</code> [Generated Java Files] folder).
It should look something like this:</p>
<pre>
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 id {
public static final int textview=0x7f050000;
}
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;
}
}
</pre>
<p>A project's <code>R.java</code> 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>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 <code>res/values/string.xml</code> file or drawables inside
the <code>res/drawable/</code> direcory) you'll see <code>R.java</code> change to keep up.</p>
<p>When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).</p>
<p><em>You should never edit this file by hand.</em></p>
</div>
<h2 id="debugging">Debug Your Project</h2>
<p>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:</p>
<pre>
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);
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>
<a href="images/hello_world_8.png"><img src="images/hello_world_8.png" style="height:230px" alt="" /></a>
<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 > Debug History > 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>
<a href="images/hello_world_9.png"><img src="images/hello_world_9.png" style="height:230px" alt="" /></a>
<h2 id="noeclipse">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 — 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="{@docRoot}guide/developing/tools/index.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 tool named "android" that can be
used to create all the source code and directory stubs for your project, as well
as an ant-compatible <code>build.xml</code> 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 created
in Eclipse, use this command:</p>
<pre>
android create project \
--package com.example.helloandroid \
--activity HelloAndroid \
--target 2 \
--path <em><path-to-your-project></em>/HelloAndroid
</pre>
<p>This creates the required folders and files for the project at the location
defined by the <em>path</em>.</p>
<p>For more information on how to use the SDK tools to create and build projects, please read
<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p>
|