Você está na página 1de 50

25/11/11 Andoid 4.

0 Deelopmen Toial
1/50 .ogella.de/aicle/Andoid/aicle.hml
Andoid 4.0 Deelopmen Toial
La Vogel
Version 8.7
Copyright 2009 - 2011 Lars Vogel
24.11.2011
Revision Histor
Revision 0.1 04.07.2009
Created
Revision 0.2 - 8.7 07.07.2009 - 24.11.2011
bug f iing and enhancements
Deelopmen ih Andoid Gingebead and Eclipe
This tutorial describes how to create Android applications with Eclipse. It is based on Eclipse 3.7
(Indigo), Java 1.6 and Android 4.0 (Ice Cream Sandwich).
Table of Conen
1. What is Android?
1.1. Android Operation System
1.2. Important Android components
1.3. Dalvik Virtual Machine
1.4. Security and permissions
2. Android Application Architecture
2.1. AndroidManifest.xml
2.2. R.java, Resources and Assets
2.3. Reference to resources in XML files
2.4. Activities and Layouts
2.5. Activities and Lifecycle
2.6. Context
3. Installation
3.1. Eclipse and automatic Android SDK
3.2. Manually install Android SDK
3.3. Install a specific Android version
3.4. Android Source Code
4. Emulator Shortcuts
4.1. Create an Android Emulator Device
4.2. Using the emulator
4.3. Performance
5. Error handling and typical problems
25/11/11 Andoid 4.0 Deelopmen Toial
2/50 .ogella.de/aicle/Andoid/aicle.hml
5.1. Clean Pojec
5.2. LogCa
5.3. Emlao doe no a
5.4. Eo meage fo @oeide
5.5. Miing Impo
5.6. Eclipe Tip
6. Yo fi Andoid pojec
6.1. Ceae Pojec
6.2. To face of hing
6.3. Ceae aibe
6.4. Add UI Elemen
6.5. Edi UI popeie
6.6. Code o applicaion
6.7. Sa Pojec
7. Saing an deploed applicaion
8. Men and Acion Ba
8.1. Definiion of men enie
8.2. Acion ba ab
8.3. Cone men
9. Toial: Men and Acion Ba
9.1. Pojec
9.2. Add a men XML eoce
10. Pefeence
11. Toial: Pefeence
11.1. Uing pefeence
11.2. Rn
12. Dialog ia he AleDialog
13. Lao
14. TableLao
14.1. Oeie
14.2. Eample
15. ConenPoide
15.1. Oeie
15.2. Ceae conac on o emlao
15.3. Uing he Conac Conen Poide
16. ScollVie
17. DDMS pepecie and impoan ie
17.1. DDMS - Dalik Debg Monio See
17.2. LogCa Vie
17.3. File eploe
18. Shell
18.1. Andoid Debgging Bidge - Shell
18.2. Uninall an applicaion ia adb
18.3. Emlao Conole ia elne
19. Deplo o applicaion on a eal deice
20. Thank o
21. Qeion and Dicion
22. Link and Lieae
22.1. Soce Code
22.2. Andoid Reoce
22.3. ogella Reoce
25/11/11 Andoid 4.0 Deelopmen Toial
3/50 .ogella.de/aicle/Andoid/aicle.hml
1. What is Android?
1.1. Android Operation Sstem
A L J . I , ..
, J V (D V
M - DVM).
A O H A G .
A 2-D 3-D OGL
SQL .
E A
A . T
A .
1.2. Important Android components
A A :
Activit - A , ..
. A A
.
Views - U A
android.view.View. T android.view.ViewGroups.
V .
Services - UI. T
A.
ContentProvider - ,
. A SQL DB

Intents -
. A ( )
A ( ). F
. A
IntentFilter. Intents
.
BroadcastReceiver - ,
. A BroadcastReceiver
.
25/11/11 Andoid 4.0 Deelopmen Toial
4/50 .ogella.de/aicle/Andoid/aicle.hml
Widgets - ieacie ce ia ed he Adid hecee dia ceai
daa ad a he e hae ic acce he he ifai
Ohe Adid ce ae Lie Fde ad Adid Lie Waae. Lie Fde dia daa
he hecee ih achig he cedig aicai.
1.3. Dalvik Virtual Machine
Adid e a ecia ia achie, e.g. he Dai Via Machie. Dai e ecia becde.
Theefe ca adad Jaa becde Adid. Adid ide a d hich a
ce Jaa Ca fie i de (Dai Eecabe) fie. Adid aicai ae aced i a
.apk (Adid Pacage) fie b he ga aapt (Adid Ae Pacagig T) T iif
deee Gge ide he Adid Deee T (ADT) f Ecie. The ADT ef
aaica he cei f ca de fie ad ceae he a dig dee.
1.4. Securit and permissions
Adid defie ceai eii f ceai a. F eae if he aicai a acce he
Iee i defie i i cfigai fie ha i d ie e he eaed eii. Dig he
iaai f a Adid aicai he e eceie a cee i hich he eed cfi he
eied eii f he aicai.
2. Android Application Architecture
2.1. AndroidManifest.ml
A Adid aicai i decibed i he fie AndroidManifest.ml . Thi fie decae a
Activities, Services, BroadcastReceivers ad ContentProvider f he aicai. I
a cai he eied eii f he aicai. F eae if he aicai eie
e acce i be ecified hee. AndroidManifest.ml ca be hgh a he dee
deci f a Adid aicai.

<?xm1 ves1on="1.0" encod1ng="uff-"?>
<man1fesf xm1ns:ando1d="hffp://schemas.ando1d.com/apk/es/ando1d"
package="de.voge11a.ando1d.fempeafue"
ando1d:ves1onCode="1"
ando1d:ves1onName="1.0">
<app11caf1on ando1d:1con="0daWab1e/1con" ando1d:1abe1="0sf1ng/appname">
<acf1v1fy ando1d:name=".Convef"
ando1d:1abe1="0sf1ng/appname">
<1nfenf-f11fe>
<acf1on ando1d:name="ando1d.1nfenf.acf1on.MAlN" />
<cafegoy ando1d:name="ando1d.1nfenf.cafegoy.LAuNChLk" />
</1nfenf-f11fe>
</acf1v1fy>
</app11caf1on>
<uses-sdk ando1d:m1n5dkves1on="9" />
</man1fesf>

The package aibe defie he bae acage f he fig Jaa eee. I a be ie
a he Adid Maeace a aicai f a ecific acage ce. Theefe a gd habi
25/11/11 Andoid 4.0 Deelopmen Toial
5/50 .ogella.de/aicle/Andoid/aicle.hml
i o e o eee domain name a a package o aoid colliion ih ohe deelope.
android:versionName and android:versionCode pecif he eion of o applicaion.
versionName i ha he e ee and can be an ing. versionCode m be an inege and he
Andoid Make e hi o deemine if o poided a nee eion o igge he pdae on deice
hich hae o applicaion inalled. Yo picall a ih "1" and inceae hi ale b one if o oll-
o a ne eion of o applicaion.
The ag <activit> define an Activit , in hi eample poining o he cla
"de.ogella.andoid.empeae.Cone". An inen file i egieed fo hi cla hich define ha
hi Activit i aed once he applicaion a (acion
android:name="android.intent.action.MAIN" ). The caego definiion categor
android:name="android.intent.categor.LAUNCHER" define ha hi applicaion i
added o he applicaion dieco on he Andoid deice. The @string/app_name ale efe o
eoce file hich conain he acal ale. Thi make i ea o poide diffeen eoce, e.g.
ing, colo, icon, fo diffeen deice and make i ea o anlae applicaion.
The "e-dk" pa of he "AndoidManife.ml" define he minimal SDK eion o applicaion i
alid fo. Thi ill peen o applicaion being inalled on deice ih olde SDK eion.
2.2. R.java, Resources and Assets
The dieco gen in an Andoid pojec conain geneaed ale. R.java i a geneaed cla hich
conain efeence o eoce of he res folde in he pojec. Thee eoce ae defined in he res
dieco and can be ale, men, lao, icon o pice o animaion. Fo eample a eoce
can be an image o an XML file hich define ing.
If o ceae a ne eoce, he coeponding efeence i aomaicall ceaed in R.java . The
efeence ae aic in ale, he Andoid em poide mehod o acce he coeponding
eoce. Fo eample o acce a Sing ih he efeence id R.string.ourString e he
mehod getString(R.string.ourString)); . R.jaa i aomaicall mainained b he
Eclipe deelopmen enionmen, manal change ae no necea.
While he dieco res conain ced ale hich ae knon o he Andoid plafom he dieco
assets can be ed o oe an kind of daa. In Jaa o can acce hi daa ia he
AssetsManager and he mehod getAssets() .
2.3. Reference to resources in XML files
In o XML file, e.g. o lao file o can efe o ohe eoce ia he @ ign. Fo eample if o
an o efe o a colo o defined a eoce o can efe o i ia @color/our_id o if o
hae defined a "hello" ing a eoce o can acce i ia @string/hello .
2.4. Activities and Laouts
The e ineface fo Activities i defined ia lao. A nime, lao ae inance of
25/11/11 Andoid 4.0 Deelopmen Toial
6/50 .ogella.de/aicle/Andoid/aicle.hml
andoid.ie.VieGop . The a defie he UI eee, hei eie ad hei
aagee.
UI eee ae baed he ca andoid.ie.Vie . VieGop i a bca f he ca
Vie ad a a ca cai UI ce ( Vie ) he a ( VieGop ). Y
hd ee VieGop dee a hi ha a egaie iac eface.
A a ca be defied ia Jaa cde ia XML. Y ica e Jaa cde geeae he a if
d' he ce i ie; f eae if a deed ce hich ead
f he Iee.
XML baed a ae defied ia a ece fie i he fde /e/lao . Thi fie ecifie he
VieGop , Vie , hei eaihi ad hei aibe f a ecific a. If a UI eee
eed be acceed ia Jaa cde hae gie he UI eee a ie id ia he andoid:id
aibe. T aig a e id a UI eee e @+id/oale . B cei hi i ceae
ad aig a e id oale he cedig UI eee. I Jaa cde ca ae
acce hee UI eee ia he ehd findVieBId(R.id.oale) .
Defiig a ia XML i a he efeed a a hi eaae he gaig gic f he
a defiii. I a a he defiii f diffee a f diffee deice. Y ca a i
bh aache.
2.5. Activities and Lifeccle
The eaig e c he ife cce f aicai. A a ie he Adid e a
de aicai, e.g. becae f a icig ca. The Adid e defie a ife cce f
aciiie ia e-defied ehd. The ia ehd ae:
onSaeInanceSae() - caed if he acii i ed. Ued ae daa ha he
acii ca ee i ae if e-aed
onPae() - aa caed if he Acii ed, ca be ed eeae ece ae daa
onReme() - caed if he Acii i e-aed, ca be ed iiiaie fied
The acii i a be eaed if a caed "cfigai chage" hae. A cfigai chage
f eae hae if he e chage he ieai f he deice (eica hia). The acii
i i hi cae eaed eabe he Adid af ad diffee ece f hee cfigai,
e.g. a f eica hia de. I he ea ca iae he chage f he ieai
ia CNTR+F11 .
Y ca aid a ea f aicai f ceai cfigai chage ia he cfigChage
aibe acii defiii i AndoidManife.ml . The fig acii i be
eaed i cae f ieai chage ii f he hica ebad (hidde / iibe).

<activity android:name=".ProgressTestActivity"
android:label="@string/app_name"
android:configChanges="orientationkeyboardHiddenkeyboard">
25/11/11 Andoid 4.0 Deelopmen Toial
7/50 .ogella.de/aicle/Andoid/aicle.hml
</activit>

2.6. Contet
The cla android.content.Contet poide he connecion o he Andoid em. I i he
ineface o global infomaion abo he applicaion enionmen. Cone alo poide acce o
Andoid Services , e.g. heLocaion Seice. A Aciiie and Seice eend he cla Contet
o can diecl acce he cone ia this .
3. Installation
The folloing ame ha o hae alead Eclipe inalled. Fo deail pleae ee Eclipe Toial .
3.1. Eclipse and automatic Android SDK
Ue he Eclipe pdae manage o inall all aailable componen fo he Andoid Deelopmen Tool
(ADT) fom he URL hp://dl-l.google.com/andoid/eclipe/ . If o ae no familia ih he Eclipe
pdae manage he age i decibed in Eclipe pdae manage .
Afe he ne Andoid deelopmen componen ae inalled o ill be pomped o inall he Andoid
SDK. Yo can do follo he folloing iad o go o he ne ecion o lean ho o do i manall.
25/11/11 Andoid 4.0 Deelopmen Toial
8/50 .ogella.de/aicle/Andoid/aicle.hml
3.2. Manuall install Android SDK
The previous step downloads the Android SDK automatically for you. You can also download the Android
SDK manuallz from the Android homepage under Android SDK download . The download contains a zip
file which you can extract to any place in your file system, e.g. I placed it under "c:\android-sdk-windows".
Avoid using spaces in the path name otherwise you may experience problems later.
You also have to define the location of the Android SDK in the Eclipse Preferences. In Eclipse open the
Preferences dialog via Windows Preferences . Select Android and enter the installation path of the
25/11/11 Andoid 4.0 Deelopmen Toial
9/50 .ogella.de/aicle/Andoid/aicle.hml
Android SDK.
3.3. Install a specific Android ersion
The Android SDK Manager allows you to install specific versions of Android. Select Window Android
SDK Manager from the Eclipse menu.
25/11/11 Andoid 4.0 Deelopmen Toial
10/50 .ogella.de/aicle/Andoid/aicle.hml
The dialog allows ou to install new package and also allow ou to delete them. Select "Available
packages" and open the "Third Part Add-ons". Select the Google API 14 (Android 4.0) version of the
SDK and press "Install".
Press the "Install" button and confirm the license for all package. After the installation restart Eclipse.
3.4. Andoid Soce Code
The following step is optional.
During Android development it is ver useful to have the Android source code available as Android uses
a lot of defaults.
Haris Peco maintains plugins which provides access to the Android Source code code. Use the Eclipse
update manager to install the Android Source plugin from the following update site: "http://adt-
addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update".
More details can be found on the project website .
4. Emlao Shoc
4.1. Ceae an Andoid Emlao Deice
The Android tools include an emulator. This emulator behaves like a real Android device in most cases
25/11/11 Andoid 4.0 Deelopmen Toial
11/50 .ogella.de/aicle/Andoid/aicle.hml
and allows you to test your application without having a real device. You can emulate one or several
devices with different configurations. Each configuration is defined via an "Android Virtual Device"
(AVD).
To define an AVD open the "AVD Manager" via Windows AVD Manager and press "New".
Enter the following.
25/11/11 Andoid 4.0 Deelopmen Toial
12/50 .ogella.de/aicle/Andoid/aicle.hml
We can alo elec he bo "Enabled" fo Snapho. Thi ill make he econd a of he ial deice
mch fae.
A he end pe he bon "Ceae AVD".Thi ill ceae he deice and dipla i nde he "Vial
deice". To e if o ep i coec, elec o deice and pe "Sa".
Afe (a long ime) o deice hold be aed.
4.2. Uing he emlao
Obiol o can e he emlao ia he keboad on he igh ide of he emlao. B hee ae alo
ome nice hoc hich ae efl.
Al+Ene maimie he emlao. Nice fo demo.
Cl+F11 change he oienaion of he emlao.
F8 n neok on / off.
25/11/11 Andoid 4.0 Deelopmen Toial
13/50 .ogella.de/aicle/Andoid/aicle.hml
4.3. Performance
T HVGA. T
.
A , 1 GB . T
"D " AVD.
A "E" S. T
.
5. Error handling and tpical problems
T . T
.
5.1. Clean Project
S :
1. P ... : ''
2. T .
3. U R..
T , P -> C.
5.2. LogCat
T LC A .
F J . T , "W -
> S V -> O -> A -> LC" .
5.3. Emulator does not start
I , -
.
5.4. Error message for @override
T @ J 1.6. I @
J J 1.6 - -> P -> J
C -> C "1.6".
5.5. Missing Imports
J J L
25/11/11 Andoid 4.0 Deelopmen Toial
14/50 .ogella.de/aicle/Andoid/aicle.hml
or declared via imports. In your editor use the click mouse click, select "Source-> Organize Imports" if
you see error message with "XX cannot be resolved to a variable".
5.6. Eclipe Tip
To work more efficient with Eclipse, select Window -> Preferences -> Java -> Editor -> Save Actions and
select that the source code should be formated and that the imports should be organized at every save.
6. Yo fi Andoid pojec
6.1. Ceae Pojec
This app is also available on the Android Marketplace. Search for "vogella" for find this example.
Select File New Other Android Android Project and create the Android project
"de.vogella.android.temperature". Enter the following.
25/11/11 Andoid 4.0 Deelopmen Toial
15/50 .ogella.de/aicle/Andoid/aicle.hml
Press "Finish". This should create the following director structure.
25/11/11 Andoid 4.0 Deelopmen Toial
16/50 .ogella.de/aicle/Andoid/aicle.hml
While "e" conain ced ale hich ae knon o he Andoid plafom he dieco "ae" can
be ed o oe an kind of daa. In Jaa o can acce hi daa ia he AeManage and he
mehod geAe().
6.2. To faces of things
The Andoid SDK allo o define ceain aifac, e.g. ing and UI', in o a, ia a ich edio and
diecl ia XML. The folloing decipion ie o e he ich UI b fo alidaion li alo he XML. Yo
can ich beeen boh hing b clicking on he ab on he loe pa of he ceen. Fo eample in he
Package Eploe elec "e/lao/main.ml".
25/11/11 Andoid 4.0 Deelopmen Toial
17/50 .ogella.de/aicle/Andoid/aicle.hml
6.3. Ceae aibe
Andoid allo o o ceae aibe fo eoce, e.g. fo ing and / o colo. Thee aibe can
be ed in o UI definiion ia XML o in o Jaa oce code.
Selec he file "e/ale/ing.ml" and pe "Add". Selec "Colo" and ene "mColo" a he name
and "#3399CC" a he ale.
25/11/11 Andoid 4.0 Deelopmen Toial
18/50 .ogella.de/aicle/Andoid/aicle.hml
Add a he fig "Sig" aibe. Sig aibe a aae he aicai a a ae
i.
Table 1. Sing Aibe
Name Vale
celi o Celi
fahenhei o Fahenhei
calc Calclae
Sich he XML eeeai ad aidae he ae.

<?ml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Convert!</string>
<string name="app_name">Temperature Converter</string>
<color name="mColor">#3399CC</color>
<string name="mClickHandler">mClickHandler</string>
<string name="celsius">to Celsius</string>
<string name="fahrenheit">to Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>

6.4. Add UI Elemen
Seec "e/a/ai." ad e he Adid edi ia a dbe-cic. Thi edi a
ceae he UI ia dag ad d ia he XML ce cde. Y ca ich beee bh
eeeai ia he ab a he b f he edi. F chagig he ii ad gig eee
ca e he ie ie.
The fig h a ceeh f he Paee ie f hich ca dag ad d e UI eee
i a. Peae e ha he "Paee" ie chage fee ie igh be a bi
diffee.
25/11/11 Andoid 4.0 Deelopmen Toial
19/50 .ogella.de/aicle/Andoid/aicle.hml
Right-click on the text object Hello World, Hello! in the layout. Select Delete on the popup menu to
remove the text object. Then, from the Palette view, select Text Fields and locate Plain Text. Drag this
onto the layout to create a text input field. All object types in the section "Text Fields derive from the class
"EditText", they just specify via an additional attribute which text type can be used.
Now select the Palette section Form Widgets and drag a RadioGroup object onto the layout. The
number of radio buttons added to the radio button group depends on your version of Eclipse. Make sure
there are two radio buttons by deleting or adding radio buttons to the group.
From the Palette section Form Widgets, drag a Button object onto the layout.
The result should look like the following.
25/11/11 Andoid 4.0 Deelopmen Toial
20/50 .ogella.de/aicle/Andoid/aicle.hml
Sich o "main.ml" and eif ha o XML look like he folloing.

<?xm1 ves1on="1.0" encod1ng="uff-"?>
<L1neaLayouf xm1ns:ando1d="hffp://schemas.ando1d.com/apk/es/ando1d"
ando1d:o1enfaf1on="vef1ca1" ando1d:1ayoufW1dfh="f111paenf"
ando1d:1ayoufhe1ghf="f111paenf">
<Ld1f1exf ando1d:1ayoufhe1ghf="Wapconfenf" ando1d:1d="0+1d/ed1f1exf1"
ando1d:1ayoufW1dfh="mafchpaenf" ando1d:fexf="Ld1f1exf"></Ld1f1exf>
<kad1oGoup ando1d:1ayoufhe1ghf="Wapconfenf" ando1d:1d="0+1d/ad1oGoup1"
ando1d:1ayoufW1dfh="mafchpaenf">
<kad1o8uffon ando1d:fexf="kad1o8uffon"
ando1d:1ayoufW1dfh="Wapconfenf" ando1d:1d="0+1d/ad1o0"
ando1d:1ayoufhe1ghf="Wapconfenf" ando1d:checked="fue"></kad1o8uffon>
<kad1o8uffon ando1d:fexf="kad1o8uffon"
ando1d:1ayoufW1dfh="Wapconfenf" ando1d:1d="0+1d/ad1o1"
ando1d:1ayoufhe1ghf="Wapconfenf"></kad1o8uffon>
</kad1oGoup>
<8uffon ando1d:fexf="8uffon" ando1d:1d="0+1d/buffon1"
ando1d:1ayoufW1dfh="Wapconfenf" ando1d:1ayoufhe1ghf="Wapconfenf"></8uffon>
</L1neaLayouf>

6.5. Edi UI popeie
If o elec a UI elemen o can change i popeie ia he popeie ie. Mo of he popeie
can be changed ia he igh moe men. Yo can alo edi popeie of field diec in XML. Tpicall
o change popeie diecl in he XML file a hi i mch fae. B he igh moe fncionali i
nice if o ae eaching fo a ceain pope.
We ill delee he inial e fo he EdiTe field in XML. Sich o he "main.ml" ab and delee he
"andoid:e="EdiTe" pope fom he EdiTe pa. Sich back o he "Gaphical Lao" ab and
check ha he e i emoed.
Ue he igh moe click on he fi adio bon o aign he "celi" ing aibe o i "e"
pope. Aign he and "fahenhei" ing aibe o he econd adio bon.
25/11/11 Andoid 4.0 Deelopmen Toial
21/50 .ogella.de/aicle/Andoid/aicle.hml
Fom no on I ame o ae able o e he popeie men on he UI elemen. Yo can eihe edi
he XML file o modif he popeie ia igh moe click.
Se he pope "Checked" o e fo he fi RadioBon. Aign "calc" o he e pope of o
bon and aign "mClickHandle" o he "onClick" pope. Se he "Inp pe" pope o
"nmbeSigned" and "nmbeDecimal" on o EdiTe.
All o ohe UI conol ae conained in a LineaLao. We an o aign a backgond colo o hi
25/11/11 Andoid 4.0 Deelopmen Toial
22/50 .ogella.de/aicle/Andoid/aicle.hml
LinearLayout. Right-click on an empty space in Graphical Layout mode, then select Other Properties
All by Name Background . Select Color and then myColor in the list.
Switch to the "main.xml" tab and verify that the XML is correctly maintained.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@color/myColor">
<EditText android:layout_height="wrap_content" android:id="@+id/editText1"
android:layout_width="match_parent" android:inputType="numberDecimalnumberSigned"></
EditText>
<RadioGroup android:layout_height="wrap_content" android:id="@+id/radioGroup1"
android:layout_width="match_parent">
<RadioButton android:layout_width="wrap_content"
android:id="@+id/radio0" android:layout_height="wrap_content"
android:text="@string/celsius" android:checked="true"></RadioButton>
<RadioButton android:layout_width="wrap_content"
android:id="@+id/radio1" android:layout_height="wrap_content"
android:text="@string/fahrenheit"></RadioButton>
</RadioGroup>
<Button android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/calc"
android:onClick="myClickHandler"></Button>
</LinearLayout>

6.6. Code our application
During the generation of your new Android project you specified that an Activit called
CovertActivit should get created. The project wizard also created the correspondig Java classs.
Change your code in ConvertActivit.java to the following. Note that the mClickHandler will
be called based on the On Click property of your button.

package de.vogella.android.temperature;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class ConvertActivity etends Activity
private EditText text;
25/11/11 Andoid 4.0 Deelopmen Toial
23/50 .ogella.de/aicle/Andoid/aicle.hml
@Override
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);

// This method is called at button click because we assigned the name to the
// "On Click propert" of the button
pub11c vo1d myClickHandler(View view) {
sW1fch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
1f (text.getText().length() == 0) {
Toast.makeText(fh1s, "Please enter a valid number",
Toast.LENGTH_LONG).show();
efun;

f1oaf inputValue = Float.parseFloat(text.getText().toString());
1f (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
e1se {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);

beak;


// Converts to celsius
p1vafe f1oaf convertFahrenheitToCelsius(f1oaf fahrenheit) {
efun ((fahrenheit - 32) * 5 / 9);

// Converts to fahrenheit
p1vafe f1oaf convertCelsiusToFahrenheit(f1oaf celsius) {
efun ((celsius * 9) / 5) + 32;


6.7. Sar Projec
To start the Android Application, select our project, right click on it, Run-As-> Android Application Be
patient, the emulator starts up ver slow. You should get the following result.
25/11/11 Andoid 4.0 Deelopmen Toial
24/50 .ogella.de/aicle/Andoid/aicle.hml
Tpe in a number, select our conversion and press the button. The result should be displaed and the
other option should get selected.
7. Starting an deploed application
After ou ran our application on the virtual device ou can start it again on the device. If ou press the
Home button ou can also select our application.
25/11/11 Andoid 4.0 Deelopmen Toial
25/50 .ogella.de/aicle/Andoid/aicle.hml
25/11/11 Andoid 4.0 Deelopmen Toial
26/50 .ogella.de/aicle/Andoid/aicle.hml
8. Menus and Action Bar
8.1. Definition of menu entries
Andoid poide o poible a o dipla global acion hich he e can elec. The fi one i
he age of he Acion Ba in he applicaion. The Acion Ba i a indo feae a he op of he acii
ha ma dipla he acii ile, naigaion mode, and ohe ineacie iem.
The econd opion i ha he app can open a men hich ho addiional acion ia a popp men.
Tpical o define o men enie in a a ha he ae added o he acion ba if fficien pace i
aailable in he acion ba and if no ha emaining men iem ae diplaed in he popp men.
The opion men and he acion ba of o acii i filled b he mehod onCeaeOpionMen() of o
acii.
In hi mehod o can ceae he men pogammaicall o o can e a pe-defined XML eoce
hich o inflae ia he cla "MenInflao". Each acii ha alead an inance of he cla aailable
and hi inance can ge acceed ia he mehod geMenInflao().
onCeaeConeMen() i onl called once. If o an o inflence he men lae o hae o e he
mehod onPepaeOpionMen().
8.2. Action bar tabs
I i alo poible o add ab o an acion ba.
8.3. Contet menus
Yo can alo aign a cone men o an UI idge (ie). A cone men i aciaed if he e "long
pee" he ie.
A cone men fo a ie i egieed ia he mehod egieFoConeMen(ie). The mehod
onCeaeConeMen() i called ee ime a cone men i aciaed a he cone men i
dicaded afe i age. The Andoid plafom ma alo add opion o o ie, e.g. "EdiTe"
poide cone opion o elec e, ec.
9. Tutorial: Menus and Action Bar
9.1. Project
Thi chape ill demonae ho o ceae and ealae a opion men hich i diplaed in he acion
25/11/11 Andoid 4.0 Deelopmen Toial
27/50 .ogella.de/aicle/Andoid/aicle.hml
bar if sufficient space is available. This example will be extended in the chapter about preferences.
Create a project "de.vogella.android.socialapp" with the activity "OverviewActivity". Change the UI in the
file "/res/layout/main.xml" to the following:

<?xm1 ves1on="1.0" encod1ng="uff-"?>
<L1neaLayouf xm1ns:ando1d="hffp://schemas.ando1d.com/apk/es/ando1d"
ando1d:1ayoufW1dfh="f111paenf"
ando1d:1ayoufhe1ghf="f111paenf"
ando1d:o1enfaf1on="vef1ca1" >
<8uffon
ando1d:1d="0+1d/8uffon01"
ando1d:1ayoufW1dfh="Wapconfenf"
ando1d:1ayoufhe1ghf="Wapconfenf"
ando1d:fexf="5hoW Pefeences" >
</8uffon>
<8uffon
ando1d:1d="0+1d/8uffon02"
ando1d:1ayoufW1dfh="Wapconfenf"
ando1d:1ayoufhe1ghf="Wapconfenf"
ando1d:fexf="Change Pefeences" >
</8uffon>
</L1neaLayouf>

9.2. Add a men XML resorce
Select your project, right click on it and select New Other Android Android XML File to create a
new XML resource.
Select the option "Menu", enter as File "mainmenu.xml" and press the button "Finish".
25/11/11 Andoid 4.0 Deelopmen Toial
28/50 .ogella.de/aicle/Andoid/aicle.hml
This will create a new file "mainmenu.xml" in the folder "res/menu" of your project. Android provides an
nice editor to edit this file, unfortunately this editor is not always automatically used. To use this editor
right-click on your menu file and select Open with Android Menu Editor .
Switch if necessary to the "Layout" tab of the editor. Press Add and select "Item". Maintain the following
value. This defines the entries in your menu. We will also define that the menu entry is displayed in the
action bar if there is sufficient space avaiable.
25/11/11 Andoid 4.0 Deelopmen Toial
29/50 .ogella.de/aicle/Andoid/aicle.hml
Change our Activit class "OverviewActivit" to the following. The OnCreateOptionsMenu method is
used to create the menu. The behavior in "onOptionsItemSelected" is currentl hard-coded to show a
Toast and will soon call the preference settings. In case ou want to disable or hide menu items ou can
use the method "onPrepareOptionsMenu" which is called ever time the menu is called.

package de.vogella.android.socialapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class OverviewActivity etends Activity {
@Oerride
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

@Oerride
public boolean onCreateOptionsMenu(Menu menu) {
25/11/11 Andoid 4.0 Deelopmen Toial
30/50 .ogella.de/aicle/Andoid/aicle.hml
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
efun true;

@Oerride
pub11c boo1ean onOptionsItemSelected(MenuItem item) {
Toast.makeText(fh1s, "Just a test", Toast.LENGTH_SHORT).show();
efun true;


Rn o applicaion. A hee i enogh pace in he acion ba o iem ill be diplaed hee. If hee
old be moe iem o cold pe "Men" on he emlao o ee hem. If o elec he men iem
o hold ee a mall info meage.
The o "Pefeence" bon ae no e acie. We ill e hem in he ne chape.
10. Pefeence
Andoid ppo he age of Pefeence o allo o o ae daa fo o applicaion. Pefeence
ae oed a ke ale. The definiion of Pefeence can alo be done ia an XML eoce.
Andoid poide he cla "PefeenceAcii" hich eend he cla Acii. PefeenceAcii
ppo he imple handling of pefeence. Thi acii can load a pefeence definiion eoce ia
he mehod addPefeenceFomReoce().
To commnicae beeen diffeen componen Andoid e Inen. Tpicall he PefeenceAcii i
aed fom anohe acii ia an Inen.
25/11/11 Andoid 4.0 Deelopmen Toial
31/50 .ogella.de/aicle/Andoid/aicle.hml
In o applicaion o can acce he pefeence manage ia he folloing:

5haedPefeences pefeences = PefeenceManage.gefDefau1f5haedPefeences{hi}

Vale can ge acce ia he ke of he pefeence eing.

5f1ng usename = pefeences.gef5f1ng{"usename", "n/a"}

To ceae o change pefeence o hae o call he edi() mehod. Once o hae changed he ale
o hae o call commi() o appl o change.

Ld1fo ed1f = pefeences.ed1f{}
ed1f.puf5f1ng{"usename", "neWva1uefouse"}
ed1f.comm1f{}

11. Toial: Pefeence
11.1. Uing pefeence
We ill conine ing he eample pojec "de.ogella.andoid.ocial".
Ceae an Andoid XML eoce "pefeence.ml" of pe "PefeenceSceen".
25/11/11 Andoid 4.0 Deelopmen Toial
32/50 .ogella.de/aicle/Andoid/aicle.hml
Open the file via right-mouse click and Open-with Android XML Resource Editor . Press Add, add a
"PreferenceCategory" and add two preferences "EditTextPreferences" to this category : "User" and
"Password".
25/11/11 Andoid 4.0 Deelopmen Toial
33/50 .ogella.de/aicle/Andoid/aicle.hml
Y ca a aiai he eie EdiTeFied, e.g. he iMehd. Add f eae he
fig aibe he XML defiii f ad ae he i ed ih .

android:inputType="textPassword"

Ceae he ca "MPefeeceAcii" ih eed PefeeceAcii. Thi acii i ad he
"efeece." ad i a aiai he ae.

package de.vogella.android.socialapp;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class MyPreferencesActivity etends PreferenceActivity {
@Oerride
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);


T ae hi ca aaiabe a a acii f Adid eed egie i i
"AdidMaife." fie. Seec "AdidMaife." ad he ab "Aicai". Sc he b f
he ie ad add e acii ia he "Add" b.
25/11/11 Andoid 4.0 Deelopmen Toial
34/50 .ogella.de/aicle/Andoid/aicle.hml
To make use of our new preference activit and the preference values we adjust the "OverviewActivit".
The first button will show the current values of the preferences via a Toast and the second button will
revert the maintained user name to demonstrate how ou could change the preferences via code.

package de.vogella.android.socialapp;
1mpof android.app.Activity;
1mpof android.content.SharedPreferences;
1mpof android.content.SharedPreferences.Editor;
1mpof android.os.Bundle;
1mpof android.preference.PreferenceManager;
1mpof android.view.Menu;
1mpof android.view.MenuInflater;
1mpof android.view.MenuItem;
1mpof android.view.View;
1mpof android.view.View.OnClickListener;
1mpof android.widget.Button;
1mpof android.widget.Toast;
pub11c c1ass OverviewActivity exfends Activity {
SharedPreferences preferences;
@Override
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.Button01);
// Initialie preferences
preferences = PreferenceManager.getDefaultSharedPreferences(fh1s);
button.setOnClickListener(neW OnClickListener() {
pub11c vo1d onClick(View v) {
String username = preferences.getString("username", "n/a");
String password = preferences.getString("password", "n/a");
showPrefs(username, password);

);
Button buttonChangePreferences = (Button) findViewById(R.id.Button02);
buttonChangePreferences.setOnClickListener(neW OnClickListener() {
pub11c vo1d onClick(View v) {

updatePreferenceValue();

);


p1vafe vo1d showPrefs(String username, String password){
Toast.makeText(
OverviewActivity.fh1s,
"Input: " + username + " and password: "
+ password, Toast.LENGTH_LONG).show();


p1vafe vo1d updatePreferenceValue(){
Editor edit = preferences.edit();
String username = preferences.getString("username", "n/a");
// We will just revert the current user name and save again
StringBuffer buffer = neW StringBuffer();
fo (1nf i = username.length() - 1; i >= 0; i--) {
buffer.append(username.charAt(i));

25/11/11 Andoid 4.0 Deelopmen Toial
35/50 .ogella.de/aicle/Andoid/aicle.hml
edit.putString("username", buffer.toString());
edit.commit();
// A toast is a view containing a quick little message for the
// user. We give a little feedback
Toast.makeText(OverviewActivity.this,
"Reverted string sequence of user name.",
Toast.LENGTH_LONG).show();


To open the new preference activit we will use the method onOptionsItemSelected(). Even though we
currentl have onl one option in our menu we use a switch to be read for several new menu entries. To
see the current values of the preferences we define a button and use the class "PreferenceManager" to
get the sharedPreferences.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;

// This method is called once the menu is selected


@Override
public boolean onOptionsItemSelected(MenuItem item) {
sitch (item.getItemId()) {
// We have onl one menu option
case R.id.preferences:
// Launch Preference activit
Intent i = ne Intent(OverviewActivity.this, MyPreferencesActivity.class);
startActivity(i);
// Some feedback to the user
Toast.makeText(OverviewActivity.this, "Enter your user credentials.",
Toast.LENGTH_LONG).show();
break;

return true;


11.2. Rn
Run our application. Press the "menu" hardware button and then select our menu item "Preferences".
You should be able to enter our user settings then press the back hardware button to return to our main
activit. The saved values should be displaed in a small message windows (Toast) if ou press our first
button. If ou press the second button the username should be reversed.
25/11/11 Andoid 4.0 Deelopmen Toial
36/50 .ogella.de/aicle/Andoid/aicle.hml
12. Dialogs ia the AlertDialog
We hae alead ed a "Toa" hich i a mall meage indo hich doe no ake he foc. In hi
chape e ill e he cla "AleDialog". AleDialog i ed o open a dialog fom o acii. Thi
modal dialog ge he foc nil he e cloe i.
An inance of hi cla can be ceaed b he bilde paen, e.g. o can chain o mehod call.
Yo hold ala open a dialog fom he cla onCeaeDialog(in) a he Andoid em manage he
dialog in hi cae fo o. Thi mehod i aomaicall called b Andoid if o call hoDialog(in).
Ceae a ne Andoid pojec "de.ogella.andoid.aledialog" ih he acii "ShoMDialog". Mainain
he folloing lao fo "main.ml".

<?xm1 ves1on="1.0" encod1ng="uff-"?>
<L1neaLayouf xm1ns:ando1d="hffp://schemas.ando1d.com/apk/es/ando1d"
ando1d:o1enfaf1on="vef1ca1" ando1d:1ayoufW1dfh="f111paenf"
ando1d:1ayoufhe1ghf="f111paenf">
<8uffon ando1d:1d="0+1d/8uffon01" ando1d:1ayoufW1dfh="Wapconfenf"
ando1d:1ayoufhe1ghf="Wapconfenf" ando1d:fexf="5hoW 51mp1e D1a1og"
ando1d:onC11ck="openMyD1a1og"></8uffon>
</L1neaLayouf>

Change he code of o acii o he folloing.

ackage de.voge11a.ando1d.a1efd1a1og
25/11/11 Andoid 4.0 Deelopmen Toial
37/50 .ogella.de/aicle/Andoid/aicle.hml
1mpof android.app.Activity;
1mpof android.app.AlertDialog;
1mpof android.app.AlertDialog.Builder;
1mpof android.app.Dialog;
1mpof android.content.DialogInterface;
1mpof android.os.Bundle;
1mpof android.view.View;
1mpof android.widget.Toast;
pub11c c1ass ShowMyDialog exfends Activity {

/** Called when the activity is first created. */
@Oerride
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);

pub11c vo1d openMyDialog(View view) {
showDialog(10);

@Oerride
pofecfed Dialog onCreateDialog(1nf id) {
sW1fch (id) {
case 10:
// Creae o AlerDialog
Builder builder = neW AlertDialog.Builder(fh1s);
builder.setMessage("This will end the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", neW DialogInterface.OnClickListener() {
pub11c vo1d onClick(DialogInterface dialog, 1nf which) {
ShowMyDialog.fh1s.finish();

);
builder.setNegativeButton("No, no", neW DialogInterface.OnClickListener() {
pub11c vo1d onClick(DialogInterface dialog, 1nf which) {
Toast.makeText(getApplicationContext(),"Activity will continue",Toast.LENGTH_LONG
).show();

);
AlertDialog dialog = builder.create();
dialog.show();

efun supe.onCreateDialog(id);


If ou run our application and click our button ou should see our dialog.
25/11/11 Andoid 4.0 Deelopmen Toial
38/50 .ogella.de/aicle/Andoid/aicle.hml
Moe on dialog can be fond on Andoid Dialog andad docmenaion.
13. Laouts
Andoid ppo diffeen defal lao manage. LineaLao p all i child elemen ino a ingle
colmn o o depending on he oienaion aibe. Ohe pe ae FameLao, RelaieLao and
TableLao.
All lao allo o defined aibe. Child can alo define aibe hich ma be ealaed b hei
paen lao. Fo eample he
14. TableLaout
14.1. Overview
In ealie chape e hae ed he LineaLao hich allo o o ack idge eical o hoional.
LineaLao can be need o achiee nice effec. Thi chape ill demonae he age of
"TableLao".
Thi lao allo o o oganie a ie ino a able foma. Yo pecif ia he ie gop "TableRo"
o fo o able. Afead o p idge ino he indiidal o.
On he "TableLao" o can define hich colmn hold ake addiional pace ia he
"andoid:echColmn" aibe. If eeal colmn hold ake he aailable pace o can pecif
25/11/11 Andoid 4.0 Deelopmen Toial
39/50 .ogella.de/aicle/Andoid/aicle.hml
hem a a comma-epaaed li. Simila o can e he aibe "andoid:hinkColmn", hich ill
o od-ap he conen of he pecified idge and he aibe "andoid:collapeColm" o define
iniiall hidden colmn. Via Jaa o can dipla / hide hee colmn ia he mehod
eColmnViible().
Colmn ill be aomaicall ceaed baed on he maimm nmbe of idge in one o. Pe defal
each idge ceae a ne colmn in he o. Yo can pecific ia "andoid:lao_colmn" he colmn
a idge hold go and ia "andoid:lao_pan" ho man colmn a idge hold ake.
Yo can alo p non TableRo in a able. Thi a o can fo eample add diide beeen o
colmn.
14.2. Eample
Ceae he pojec "de.ogella.andoid.lao.able" ih he acii "DemoTableLao". Change
"main.ml" o he folloing.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout android:layout_width="match_parent"
android:id="@+id/tableLayout1" android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/tableRow1">
<EditText android:text="Field1" android:id="@+id/editText1"
android:layout_width="wrap_content" android:layout_height="wrap_conte
nt"></EditText>
<EditText android:text="Field2" android:id="@+id/editText2"
android:layout_width="wrap_content" android:layout_height="wrap_conte
nt"
android:layout_column="2"></EditText>
</TableRow>
<View android:layout_width="wrap_content" android:id="@+id/view1"
android:layout_height="4px" android:background="#FF0000"></View>
<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText android:layout_height="wrap_content" android:text="Field3"
android:layout_width="wrap_content" android:id="@+id/editText3"></Edi
tText>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Field4"
android:id="@+id/editText4"></EditText>
</TableRow>
</TableLayout>
<Button android:text="Hide second column" android:id="@+id/collapse"
android:onClick="toggleHiddenRows" android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>

Change he acii "DemoTableLao" o he folloing o e he bon o hide he econd colmn in
he able.

package de.vogella.android.layout.table;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
public class DemoTableLayout etends Activity
25/11/11 Andoid 4.0 Deelopmen Toial
40/50 .ogella.de/aicle/Andoid/aicle.hml
p1vafe TableLayout layout;
p1vafe Button button;

/** Called when the activity is first created. */
@Oerride
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (TableLayout) findViewById(R.id.tableLayout1);
button = (Button) findViewById(R.id.collapse);

pub11c vo1d toggleHiddenRows(View view) {
// Second ro has inde 1
layout.setColumnCollapsed(1, !layout.isColumnCollapsed(1));
1f (layout.isColumnCollapsed(1)) {
button.setText("Show second column");
e1se {
button.setText("Hide second column");


15. ContentProvider
15.1. Overview
ConenPoide ae ed o poide daa fom an applicaion o anohe. ConenPoide do no oe
he daa b poide he ineface fo ohe applicaion o acce he daa.
The folloing eample ill e an eiing cone poide fom "Conac".
15.2. Create contacts on our emulator
Fo hi eample e need a fe mainained conac. Selec he home men and hen he men en
"People" o ceae conac.
25/11/11 Andoid 4.0 Deelopmen Toial
41/50 .ogella.de/aicle/Andoid/aicle.hml
The app will ask ou if ou want to login. Either login or select "Not now". Press ""Create a new contact".
You can create local contacts.
25/11/11 Andoid 4.0 Deelopmen Toial
42/50 .ogella.de/aicle/Andoid/aicle.hml
F . A + .A
.
15.3. Using the Contact Content Proider
C A "..." "CV".
R TV "". D .
A _ "_".
T . .

<?xm1 ves1on="1.0" encod1ng="uff-"?>
<L1neaLayouf xm1ns:ando1d="hffp://schemas.ando1d.com/apk/es/ando1d"
ando1d:o1enfaf1on="vef1ca1" ando1d:1ayoufW1dfh="f111paenf"
ando1d:1ayoufhe1ghf="f111paenf">
<1exfv1eW ando1d:1ayoufW1dfh="f111paenf"
ando1d:1ayoufhe1ghf="f111paenf" ando1d:1d="0+1d/confacfv1eW" />
</L1neaLayouf>

A
. O AM., P . O
"A" , "U P". F -
"..READ_CONTACTS".
C .
25/11/11 Andoid 4.0 Deelopmen Toial
43/50 .ogella.de/aicle/Andoid/aicle.hml

package de.vogella.android.contentprovider;
1mpof android.app.Activity;
1mpof android.database.Cursor;
1mpof android.net.Uri;
1mpof android.os.Bundle;
1mpof android.provider.ContactsContract;
1mpof android.widget.TextView;
pub11c c1ass ContactsView exfends Activity {

/** Called when the activity is first created. */
@Override
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView contactView = (TextView) findViewById(R.id.contactview);
Cursor cursor = getContacts();
Wh11e (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");


p1vafe Cursor getContacts() {
// Run quer
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = neW String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME ;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
efun managedQuery(uri, projection, selection, selectionArgs,
sortOrder);


Tpicall o old dipla ch daa in a LiVie.
16. ScrollVie
ScollVie can be ed o conain one ie ha migh be o big o fi on one ceen. If he ie i o big
he ScollVie ill dipla a coll ba o coll he cone. Of coe hi ie can be a lao hich can
hen conain ohe elemen.
Ceae an andoid pojec "de.ogella.andoid.collie" ih he acii "ScollVie". Ceae he
folloing lao and cla.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:fillViewport="true">
<LinearLayout android:id="@+id/LinearLayout01" android:orientation="vertical" android:layout_width="f
ill_parent" android:layout_height="wrap_content">
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_hei
ght="wrap_content" android:text="This is a header" android:textAppearance="?android:attr/textAppearan
ceLarge" android:paddingLeft="8dip" android:paddingRight="8dip" android:paddingTop="8dip"></TextView>
<TextView android:text="@+id/TextView02" android:id="@+id/TextView02" android:layout_width="w
25/11/11 Andoid 4.0 Deelopmen Toial
44/50 .ogella.de/aicle/Andoid/aicle.hml
rap_content" android:layout_height="fill_parent" android:layout_weight="1.0"></TextView>

<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:la
yout_height="wrap_content">
<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout
_height="wrap_content" android:text="Submit" android:layout_weight="1.0"></Button>
<Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout
_height="wrap_content" android:text="Cancel" android:layout_weight="1.0"></Button>
</LinearLayout>
</LinearLayout>
</ScrollView>


package de.vogella.android.scrollview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ScrollView etends Activity {

/** Called when the activity is first created. */
@Oerride
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.TextView02);
String s="";
for (int i=0; i < 100; i++) {
s += "vogella.de ";

view.setText(s);


The aibe "andoid:fillViepo="e"" ene ha he he collie i e o he fll ceen een if
he elemen ae malle hen one ceen and he "lao_eigh" ell he andoid em ha hee
elemen hold be eended.
25/11/11 Andoid 4.0 Deelopmen Toial
45/50 .ogella.de/aicle/Andoid/aicle.hml
17. DDMS pepecie and impoan ie
17.1. DDMS - Dalik Debg Monio See
Eclipse provides a perspective for interacting with your Android (virtual) device and your Android
application program. Select Window Open Perspective Other DDMS to open this perspective. It
includes several views which can also be used independently and allows to place calls and send SMS to
the device. It also allow to set the current geo position and to perform a performance trace of your
application.
17.2. LogCa Vie
You can see the log (including System.out.print() statements) via the LogCat view.
25/11/11 Andoid 4.0 Deelopmen Toial
46/50 .ogella.de/aicle/Andoid/aicle.hml
17.3. File eplorer
The file eplorer allos to see the files on the android simulator.
18. Shell
18.1. Android Debugging Bridge - Shell
25/11/11 Andoid 4.0 Deelopmen Toial
47/50 .ogella.de/aicle/Andoid/aicle.hml
Y ca acce Adid ea a ia he ce. Oe a he, ich "adid-d"
iaai diec i he fde "". Sa he he ia he fig cad "adb he".

adb shell

Y ca a c fie f ad deice ia he fig cad.

// Assume the gesture file exists on your Android device
adb pull /sdcard/gestures /test
// Now copy it back
adb push /test/gesture /sdcard/gestures2

Thi i cec deice ad gie Li cad ie acce he deig fie
e, e.g. , , di, ec. The aicai daa i ed i he diec
"/daa/daa/acage_f__a".
If hae eea deice ig ca ie cad e idiida deice.

# Lists all devices
adb devices
#Result
List of devices attached
emulator-5554 attached
emulator-5555 attached
# Issue a command to a specific device
adb -s emulator-5554 shell

18.2. Uninall an applicaion ia adb
Y ca ia a adid aicai ia he he. Sich he he daa/a diec (cd /daa/a)
ad i deee adid aicai.
Y ca a ia a a ia adb ih he acage ae.

adb uninstall <packagename>

18.3. Emlao Conole ia elne
Aeaie adb ca a e ee cec he deice. Thi a iae ceai
hig, e.g. icig ca, chage he e "abii", e ce gecde, ec. Ue "ee
cah 5554" cec iaed deice. T ei he ce ei, e he cad
"i" "ei".
F eae chage he e eig f he, eceie a ad ge a icig ca
ae he fig.

# connects to device
telnet localhost 5554
# set the power level
power status full
power status charging
25/11/11 Andoid 4.0 Deelopmen Toial
48/50 .ogella.de/aicle/Andoid/aicle.hml
# make a call to the device
gsm call 012041293123
# send a sms to the device
sms send 12345 Will be home soon
# set the geo location
geo fi 48 51

For more information on the emulator console please see Emulator Console manual
19. Deplo our application on a real device
Turn on "USB Debugging" on our device in the settings. Select in the settings Applications >
Development, then enable USB debugging. You also need to install the driver for our mobile phone. For
details please see Developing on a Device . Please note that the Android version ou are developing for
must be the installed version on our phone.
To select our phone, select the "Run Configurations", select "Manual" selection and select our device.
20. Thank ou
Please help me to support this article:

21. Questions and Discussion
Before posting questions, please see the vogella FAQ . If ou have questions or find an error in this
25/11/11 Andoid 4.0 Deelopmen Toial
49/50 .ogella.de/aicle/Andoid/aicle.hml
aice eae e he .gea.de Gge G . I hae ceaed a h i h ceae gd
ei hich igh a he .
22. Link and Lieae
22.1. Soce Code
Sce Cde f Eae
22.2. Andoid Reoce
Adid 2 (Gea B)
Adid LiVie ad LiAcii
Adid SQie Daabae
Adid Widge
Adid Lie Waae
Adid Seice
Adid Lcai API ad Gge Ma
Adid Ie
Adid ad Neig
Adid Heage
Adid Deee Heage
Adid Ie / Bg
Adid Gge G
Adid Lie Fde
22.3. ogella Reoce
Ecie RCP Taiig (Gea) Ecie RCP Taiig ih La Vge
Adid Tia Idci Adid Pgaig
GWT Tia Pga i Jaa ad cie JaaSci ad HTML
Ecie RCP Tia Ceae aie aicai i Jaa
JUi Tia Te aicai
25/11/11 Andoid 4.0 Deelopmen Toial
50/50 .ogella.de/aicle/Andoid/aicle.hml
Git Tutorial Put everthing ou have under distributed version control sstem

Você também pode gostar