surviving android programming with android studio · qwertyuiopasdfghjklzxcvbnmqwertyuio...

216
qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop asdfghjklzxcvbnmqwertyuiopasdfghjklz xcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop asdfghjklzxcvbnmqwertyuiopasdfghjklz xcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop asdfghjklzxcvbnmqwertyuiopasdfghjklz xcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop Surviving Android Programming with Android Studio Version 1 ‐ 2017 Ahmad Hanis Mohd Shabli

Upload: others

Post on 16-Apr-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

qwertyuiopasdfghjklzxcvbnmqwertyuio

pasdfghjklzxcvbnmqwertyuiopasdfghjkl

zxcvbnmqwertyuiopasdfghjklzxcvbnmq

wertyuiopasdfghjklzxcvbnmqwertyuiop

asdfghjklzxcvbnmqwertyuiopasdfghjklz

xcvbnmqwertyuiopasdfghjklzxcvbnmq

wertyuiopasdfghjklzxcvbnmqwertyuiop

asdfghjklzxcvbnmqwertyuiopasdfghjklz

xcvbnmqwertyuiopasdfghjklzxcvbnmq

wertyuiopasdfghjklzxcvbnmqwertyuiop

asdfghjklzxcvbnmqwertyuiopasdfghjklz

xcvbnmqwertyuiopasdfghjklzxcvbnmq

wertyuiopasdfghjklzxcvbnmqwertyuiop

Surviving Android Programming with Android Studio 

 

Version1‐2017

AhmadHanisMohdShabli

Page 2: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

i

Copyright©2017byAhmadHanis

All rights reserved. No part of this publicationmay be reproduced, distributed, or

transmittedinanyformorbyanymeans,includingphotocopying,recording,orother

electronicormechanicalmethods,withoutthepriorwrittenpermissionofthewriter,

except in thecaseofbriefquotationsembodied incritical reviewsandcertainother

non‐commercial uses permitted by copyright law. For permission requests,write to

thewriter,addressed“Attention:PermissionsCoordinator,”attheaddressbelow.

AhmadHanisMohdShabliSchoolofComputing,CollegeofArtsandSciences,UniversitiUtaraMalaysia,06010Sintok,KedahHp:+60194702493Email:[email protected]

Page 3: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

ii

Preface 

Android has become one of the most dominant mobile operating system for smart

mobile devices. It is estimated that almost 70 percent ofworld smartmobile devices

market dominated by Android operating system. Android is an open source mobile

operating system thus making it popular among smart mobile device manufacturer.

Developercanfreelydownloadandmodifytheoperatingsystemtosuitetheirhardware

needs. Thishas spawnmanyAndroidbaseddeviceswithvarioussizesandhardware

specificationsthusallowingmorepeopletohaveaccesstothisoperatingsystem.

AndroidalsoprovideaplatformcalledGooglePlay,amarkettypeapplicationthatallow

user to download applications, games, music, video and book. This platform allows

developertouploadtheirapplicationorcontentandsellitworldwide.GooglePlaynow

hostedmorethanamillionapplicationsandgamesandthenumberincreasingrapidly.

Google also provide easy to use Android software development kit for developer to

developtheirapplicationanduploadtoGooglePlay.

Thisbookcoversbasic introduction toAndroidprogrammingusingAndroidStudioas

its main medium. There are many third party development environments such as

Eclipse, Intel XDK, App Inventor, Basic4android, Corona, and etc. However Android

Studio is the default Android Integrated Development Environment (IDE) where it’s

fully supported by Google. Any new update to its SDK will be effortlessly updated

throughAndroidStudiotools.NeverthelessAndroidStudioprovidedthenativecodefor

Androidapplicationwhereanyapplicationsgeneratedareoptimizedfortheoperating

system.

ThisbookintendedforpeoplewhoareinterestedindevelopingAndroidapplicationbut

lackofexperiencewithAndroidprogrammingorasaquickreferencesforexperienced

programmer for developing their program. The only basic requirement of

understandingthisbookisthatreadermusthavesomebasicideaofprogrammingand

alsounderstandingofhowcomputersystemandsoftwareworks.Clearunderstanding

of the concept some programming concepts such as of compiler, function, object

oriented programming, classes, and so on can further accelerate understanding the

contentofthisbook.SomebasicknowledgeinJavaprogrammingwillalsogreatlyspeed

upthelearningcurve.

Every topicdiscuss in thisbookuse thesimplestmethodpossible so thatpeoplewho

had limited programming knowledge can still digest and use in their Android

application project. This book startedwith installation of Android Studio inWindows

Page 4: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

iii

and some requirements needed. Then it continue with the infamous “hello world”

induction program that provide reader with the basic idea basic how Android

programming is structured and works. Each topic after “Hello World” then will

introducereaderwithsomecommoninterfacecomponentssuchasbuttonandtextview

andhow to use in a project. Each topic of this bookprogressing little by little adding

moreandmorelayoutcomponentthatshouldbeenoughtogetusercomfortablewith

Androidprogrammingbutwithoutgoingtoomuchdeeperandconfusing.

Surviving the Book 

This book basically is a collection of the author own vast experience from training,

teachinganddevelopingAndroidapplications. Itemploysmethodnormallyuseby the

author during training or classes. This book will cover all basic aspect of Android

programming starting from preparation of development environment with eclipse,

designing of the application layout and programming instruction for most common

layoutcomponentfunctions.Italsocoversbasicdatabaseoperation(online,offlineand

real‐time),sensors,GoogleMap,serviceandetc.Readershouldbeabletobecompetent

indevelopingbasicAndroidapplicationoncecompletingthisbook.

Page 5: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

iv

Page 6: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

v

Contents Preface.....................................................................................................................................................................ii

SurvivingtheBook.........................................................................................................................................iii

1.0PREPARINGANDROIDDEVELOPMENTENVIRONMENT..........................................................1

1.1MachineSpecification............................................................................................................................2

1.2JavaDevelopmentKit(JDK)................................................................................................................2

1.3AndroidStudio..........................................................................................................................................4

1.4AndroidSoftwareDevelopmentKit(AndroidSDK)................................................................6

1.5AndroidVirtualDevice(AVD)............................................................................................................6

1.6RunonRealAndroidDevice...............................................................................................................8

1.7TestingtheDevelopmentEnvironment(HelloWorld)........................................................10

1.8GettingtoknowAndroidStudioIDE.............................................................................................17

1.9Dissecting“HelloWorld”Project....................................................................................................19

ACVITITY_MAIN.XML..................................................................................................................................19

MainActivity.java......................................................................................................................................21

2.0BASICCOMPONENTPROGRAMMING...............................................................................................23

2.1AboutConstraintLayout(IMPORTANT!!!)................................................................................24

2.2TextView,EditText,andButton......................................................................................................25

2.2.1TextView...............................................................................................................................................25

Project1‐TextView.................................................................................................................................26

3.2Button..........................................................................................................................................................31

Project2‐Button......................................................................................................................................31

CodeDescription.......................................................................................................................................33

3.3UnderstandingToast............................................................................................................................34

3.4TextFields.................................................................................................................................................34

Project3–TextFields............................................................................................................................35

CodeDescription.......................................................................................................................................37

CodeDescription.......................................................................................................................................38

SomeUseful“Trick”forEditText...........................................................................................................38

Page 7: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

vi

EmptyUserInputError.........................................................................................................................38

3.0SIMPLEAPPLICATIONUSINGBASICCOMPONENT...................................................................40

3.1SimpleCalculator...................................................................................................................................41

Instruction...................................................................................................................................................41

Codedescription.......................................................................................................................................43

3.2BMICalculator.........................................................................................................................................43

Instructions.................................................................................................................................................43

3.3FunwithName........................................................................................................................................46

Instructions.................................................................................................................................................46

CodeDescription.......................................................................................................................................47

3.4CompletingSimpleCalculator..........................................................................................................48

Instructions.................................................................................................................................................48

CodeDescription.......................................................................................................................................49

4.0COMMONERRORINANDROIDSTUDIOPROGRAMMING.......................................................51

4.1Unfortunatelyapphasstopped.......................................................................................................52

4.2InfamousR.error...................................................................................................................................53

4.3ComponentIdnotavailable..............................................................................................................53

4.4UsingtheLogutilities..........................................................................................................................54

4.5ExceptionErrorCatch..........................................................................................................................55

5.0OTHERLAYOUTCOMPONENTS...........................................................................................................56

5.1Togglebutton...........................................................................................................................................57

Instruction...................................................................................................................................................57

MethodDescription.................................................................................................................................58

5.2CheckBox..................................................................................................................................................58

Instruction...................................................................................................................................................58

CodeDescription.......................................................................................................................................59

5.3RadioButtonwithRadioGroup.......................................................................................................60

Instruction...................................................................................................................................................60

MethodDescription.................................................................................................................................61

Page 8: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

vii

5.4Spinner........................................................................................................................................................62

Instruction...................................................................................................................................................62

CodeDescription.......................................................................................................................................63

5.5Switch..........................................................................................................................................................64

Instruction...................................................................................................................................................64

CodeDescription.......................................................................................................................................65

5.6ListView......................................................................................................................................................65

Instruction...................................................................................................................................................66

Description..................................................................................................................................................67

6.0UNDERSTANDINGLISTENER...............................................................................................................69

6.1ButtononClickListener........................................................................................................................70

Instruction...................................................................................................................................................70

CodeDescription.......................................................................................................................................71

6.2ButtononLongClickListener............................................................................................................71

Instruction...................................................................................................................................................72

6.3ImplementingListenerwithinonCreate.....................................................................................73

6.4ImplementingListeneronclass......................................................................................................73

7.0LAYOUTMANAGER....................................................................................................................................75

7.1TypeofLayout..............................................................................................................................................76

7.1.1ConstraintLayout...............................................................................................................................76

7.1.2LinearLayout.......................................................................................................................................77

7.1.3RelativeLayout....................................................................................................................................78

7.1.4TableLayout.........................................................................................................................................78

7.1.5AbsoluteLayout(notrecommended)......................................................................................79

7.1.6FrameLayout.......................................................................................................................................79

7.1.7ListviewLayout...................................................................................................................................79

Instruction...................................................................................................................................................80

7.8CustomListview.....................................................................................................................................82

Instruction...................................................................................................................................................82

Page 9: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

viii

7.1.9SimpleTabLayout.............................................................................................................................84

Instruction...................................................................................................................................................84

7.2SupportingDifferentScreenSize.........................................................................................................87

7.2.1Usewrap_contentandmatch_parent........................................................................................87

7.2.2ScrollView.............................................................................................................................................88

7.2.3Layoutweightsumandlayoutweight.......................................................................................89

8.0MULTIMEDIA................................................................................................................................................91

8.1ImageView................................................................................................................................................92

Instruction...................................................................................................................................................92

CodeDescription.......................................................................................................................................94

Assignment..................................................................................................................................................94

8.2MediaPlayer.............................................................................................................................................95

Instruction...................................................................................................................................................95

CodeDescription.......................................................................................................................................96

Assignment..................................................................................................................................................97

9.0INTERFACEDESIGNSUGGESTION.....................................................................................................98

10.1ScrollViewLayout...............................................................................................................................99

9.2ChangingComponentBackgroundColour..............................................................................100

9.3IconDesign.............................................................................................................................................101

9.4CustomButton......................................................................................................................................102

Instruction................................................................................................................................................102

CodeDescription....................................................................................................................................104

9.5ButtonClickEffect..............................................................................................................................104

9.6CustomTextEdit.................................................................................................................................104

Instruction................................................................................................................................................105

Description...............................................................................................................................................106

9.6Border......................................................................................................................................................106

10.0UNDERSTANDINGMENU..................................................................................................................108

10.1AndroidMenu....................................................................................................................................109

Page 10: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

ix

Instruction................................................................................................................................................109

Description...............................................................................................................................................110

10.2PopupMenu........................................................................................................................................110

Instruction................................................................................................................................................111

Description...............................................................................................................................................112

10.3ActionBar............................................................................................................................................112

EnablingActionBarButton..............................................................................................................113

11.0INTENT......................................................................................................................................................115

11.1LayoutIntent......................................................................................................................................116

Instruction................................................................................................................................................116

Description...............................................................................................................................................118

11.2Caller......................................................................................................................................................118

Instruction................................................................................................................................................118

11.2SMS..........................................................................................................................................................119

Instruction................................................................................................................................................119

12.0ASYNCTASKANDWEBSERVICES..................................................................................................121

12.1Asynctask.............................................................................................................................................122

Instruction................................................................................................................................................122

12.2WebService........................................................................................................................................124

Instruction................................................................................................................................................124

13.0ANDROIDDATASTORAGE...............................................................................................................127

13.1SharedPreference............................................................................................................................128

Instruction................................................................................................................................................128

13.2OfflineDatabaseApplication......................................................................................................131

Instruction................................................................................................................................................131

13.3OnlineDatabase(MySQL)............................................................................................................137

Instruction................................................................................................................................................138

14.0BROADCASTRECEIVERS,SERVICE,ALARMMANAGER....................................................168

14.1BroadcastReceivers........................................................................................................................169

Page 11: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

x

RegisteringviaManifest.....................................................................................................................169

RegisterBroadcastProgrammatically.........................................................................................171

14.2AndroidService.................................................................................................................................173

Instruction................................................................................................................................................173

14.3AlarmManager..................................................................................................................................176

ExampleApplication:MusicPlayerasService.........................................................................176

15.0SENSORS,GOOGLEMAPANDLOCATIONMANAGER..........................................................178

15.1Sensor....................................................................................................................................................179

GetAllAvailableSensors....................................................................................................................179

Accesstospecificsensor....................................................................................................................179

15.2GoogleMap..........................................................................................................................................181

Preparation...............................................................................................................................................181

GoogleMapProject...............................................................................................................................182

15.3GoogleMapObjectManipulation..............................................................................................186

15.3LocationManager.............................................................................................................................189

Instruction................................................................................................................................................189

15.4GeocoderandReverseGeocoder..............................................................................................191

GeocoderExample................................................................................................................................191

ReverseGeoCoderExample..............................................................................................................193

16.0PUBLISHINGANDROIDAPPLICATION.......................................................................................195

16.1Registration.........................................................................................................................................196

16.2ApplicationUploadPreparation................................................................................................198

TheAuthor..........................................................................................................................................................204

Page 12: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop
Page 13: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

1

       

TOPIC 1 1.0 PREPARING ANDROID DEVELOPMENT ENVIRONMENT 

Preparing good IDE (Integrated Development Interface) is important to have smooth

codingexperienceandalsoreduceanyproblemduringprojectdevelopmentlater.There

are three components required in preparing development environment for Android

programming; Java Development Kit (version 1.8), Android Studio (version 2.3), and

AndroidSDK.Thisbookusesthelatestversionofsoftware’savailableduringthewriting

ofthisbook(6/2017).

Page 14: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

2

1.1 Machine Specification 

Allprogrammingexampleinthisbookrunonthefollowingmachinespecification:

Operating

system

Windows

10

Processor IntelI764bit

Memory 8GB

Storage 1TB

It is also recommended to have the best hardware specification so that development

environmentwill be smooth and fast. However, the lowers specification is at least to

have4GBofmemorywithIntel I5orequivalent.But theperformanceof thesoftware,

compilerandvirtualmachine(Androidsimulationsoftware)aretobeexpectedtowork

at minimal operational function. Make sure the machine also not running any

backgroundmemoryintensiveapplicationsuchasPhotoshoporvideoeditionsoftware.

Anotheroptionalbuthighlyrecommendedupgradeistochangethetraditionaldriveto

solid stated drive (SSD). SSD provide significant upgrade to the computer where it

provides faster data transfer rate. On average computer can boot up within 5‐10

secondsandrunapplicationwith50‐100percentfasterthannormaldrive.However,the

priceofSSDdrivecanbequiteexpensivewherefor120GBSSDdrivecancostaround

RM200‐RM300.Theupgrademustbeaccompaniedwithfreshinstallationofoperating

systemtothedrive.Theolddrivethensetassecondarydrivefordatastorageandifthe

installation is done on a notebook, the DVD drive no longer can be used due to

relocationofthesecondarydrive.

1.2 Java Development Kit (JDK) 

Android programming platform is based on Java programming language; thus Java

developmentenvironment isneededinthedevelopmentmachine. JDKprovideall the

necessarycomponentstocompileandrunJavabasedcode.Itcanbedownloadedfrom

Oracle official website freely. Download the latest version of JDK SE from

http://www.oracle.com/technetwork/Java/javase/downloads/jdk8‐downloads‐

2133151.html. The latest version during the time of this book is version 1.8. Once

downloaded proceed with installation as usual until completion. The installation is

prettymuchasimpleprocessoffollowingtheguidelineoftheInstaller.Onceinstallation

hadcompletedchecktheinstalledJavaversionbytypingthefollowingcommandfrom

Windowscommandprompt.ThisbookusesthefollowingJavaversion

Page 15: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

3

If Java jdk had successfully installed and configured correctly by the installer, Java

versionmessageshouldappearinthecommandprompt.Sometimestheinstallermight

misstheWindowsenvironmentsetting.Ifthecommandfailedtoshowpleaseproceed

withsystemenvironmentsettingasfollow.

AfewWindowspathenvironmentsettingsarerequiredtouseJDKcompileraseasyas

possible later. However this reference onlyworks forWindows 10 and not for other

OperatingSystem.NeverthelessotherversionofWindowsshouldhavethesameideain

having the path set to system environment. It is necessary to set path to the system

environmentvariabletotheJavabinpathdirectory.TosetdirectorypathopenControl

Panel\System and Security\SystemProperties and open Advanced System setting

option.AccesstheEnvironmentVariablebuttonandsetpathforbothuserandsystem

variables.

PathvariablesonbothuserandsystemvariableshouldpointtothedirectoryofJavabin

path.AfteraddingtheJavabindirectorytobothvariablepathandpressoktocomplete

thesetting.

Page 16: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

4

Totesttheenvironmentsetting,restartcomputerandopencommandpromptandenter

Java –version command from any command prompt directory. The command should

return JDK version information. If it returns command not found, check the path

directoryinthesystemenvironmentagain.

DuetorecentupdatetoAndroidStudio,JDKisnolongerrequiredsinceeverythinghas

been included intherecentAndroidStudio Installer.Unlessthere’saneed forspecific

JDKfunctionsthatisonlyavailableinOracleJDKpackage,theInstallationofOracleJDK

is no longer required. A statement from Android website is available here

https://developer.android.com/studio/intro/studio‐config.html.

1.3 Android Studio 

AndroidStudioistheofficialIDEforAndroidappdevelopmentfullysupported.TheIDE

previouslyknownasonIntelliJIDEAprovidedpowerfulcodeeditoranddevelopertools

thathelpuser to easilymanage anddeploy theirmobile appandgames.TheAndroid

Studioversionusesthroughoutthisbookisfromversion2.3.

Download the latest version of Android Studio from the following link

https://developer.android.com/studio/index.html. Look for the download button and

proceedwiththedownload.Beawarethatthesizeoftheinstallationfileisalmost2GB.

Makes sure to download the installer in a fast and stable Internet connection with

enough free storage space in computer. Accept the agreement for the downloading

process.

Page 17: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

5

TheinstallercontainsallthebundledapplicationsthatneededtoruntheIDE.Oncethe

downloadcompleted,runtheinstallerandfollowalltheonscreeninstallerinstruction.

Thefinalinstallationprocessshouldshowthefollowingscreen:

It ishighlyrecommended tohave Internetconnectionwhen for the first timerunning

theAndroidStudio. TheIDEwillperformseveraldownloadandupdatetosomeofits

platformcomponentsandpluginstothelatestversion.Followtheonscreeninstallation

instruction.

Onceallrequiredcomponenthasbeencompletelydownloaded,userwillbepresented

withthefollowinguserinterface.

Page 18: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

6

1.4 Android Software Development Kit (Android SDK) 

The third important component in in preparing Android programming development

environmentisAndroidSDK.AndroidSDKprovidedbyGoogletoenabledeveloperwith

all thenecessaryprogrammingAPIandtools todevelopAndroidapplication.TheSDK

comespreinstalledwiththeAndroidStudio.Thereisnoneedtodownloadconfigurethe

AndroidSDKseparatelyforAndroidStudio.

However if developer chooses to use different IDE the SDK can be downloaded from

https://developer.android.com/studio/index.html. Go the section command line tools

onlyanddownloadthecompresszipversion.

1.5 Android Virtual Device (AVD) 

AVD is a virtual device that allows developer to test their application on the desktop

withhavingaphysicalAndroiddevice.ItisafullvirtualAndroidoperatingsystemthat

developer can directly compile their project andmaking sure their applicationworks

justlikeinrealdevice.AndroidSDKprovideAVDmanagerapplicationtocreateandrun

AVD.HoweveratleastoneAPIversioninstalledneededintheSDKManager(asdescribe

before).

TocreateanewAVD,selectWindowmenuandselectAndroidVirtualDeviceManager.

Selectcreatebuttonandfillinalltherequiredinformation.

Selectioncriteriadefinedinthefollowingtable:

Page 19: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

7

AVDName: Anynames

Device: Selectresolutionrequiredtotestyourapplication.

Target: SelecttargetAPIforAVDtorunwith.(Thelistdeterminedbydownloaded

API)

CPU/ABI: Processoremulator(DeterminedalsobydownloadedAPICPU)

Skin: Withdynamichardwarecontrol

The rest of setting should set to default and press ok button to save. Select the AVD

name fromthe listandpressstartbuttontostartyourAVD. It isrecommendedtoset

scaletorealdevicefromLaunchOptionswindow.ThisshouldavoidAVDtoappeartoo

bigonthescreen(4inchrecommendedonstandardnotebook).

It may takes around 3‐4 minutes for AVD to fully operated (depend on computer

hardwareperformance)andsometimes10‐15minutesonslowcomputer.ButonceAVD

isrundonotcloseitthroughoutthedevelopmentofproject.OnlyrestartAVDifEclipse

unablerecognizedthevirtualdevicethuscannotcompileproject.

AVD is not the only method to test Android application. There are many Android

emulatorsthatavailable.OtheremulatorsuchasGenymotionorBluestackcanbeagood

replacementforAVD.

Page 20: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

8

1.6 Run on Real Android Device 

AVD needs a lot of system resources to run and can sometime quite frustrating

experiencetouse.ItisalwaysbettertobeabletorundirectlyonarealAndroiddevice.

ThereareafewstepstoenableAndroiddevicedeveloperfunction.

Enable Developer options menu ‐ Access the Android settings and look for “About

device”. One of the list in this interface is Build number that provide device build

number.Clickonthisquicklymultipletimesandpopupmessagesshouldappearabout

enabling the developer mode. Continue clicking on this until final message shows

Developermode has been turn on. Go back to settings then a newmenu “Developer

options”shouldappearasthefollowingpicture.

ThereareanumberofoptionswithinDeveloperoptionsmenu.EnableUSBdebugging

allowingcomputertorecognizethefunctionwhendeviceconnected.

Page 21: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

9

ThenlookforSecuritymenuwithinsettingsandcheckfor“Unknownsources”.

The final step is to install the requireddriverneeded for thedevice.ConnectAndroid

devicetocomputerandwaituntiltheautomaticdriverinstallationcompleted.Mostof

thetime,Windowsareabletoinstalltherequireddriver.Totestifdebuggingfeatures

can be used, reconnect the device and the following message will appear. Allow for

“Always allow from this computer” option. This is the indicator if the installation is

successful.

If this message is not appearing means the driver installation wasn’t successful and

extrastepneededtoinstallthedesireddriver.DownloadspecificdriverfortheAndroid

Page 22: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

10

device and test again. Also try to use Android universal driver from the following

website https://androidmtk.com/download‐universal‐adb‐driver. Download and

runthesoftware. It shouldbeable todetect thedeviceconnectedbutwith thewrong

driverinstalled.Selectthedeviceandinstallthedriver.Oncecompleted,disconnectthe

cableandreconnect.TheAllowUSBDebuggingshouldappear.

1.7 Testing the Development Environment (Hello World)  

Tomakesurealltheconfigurationsworks,trytocreateanewAndroidapplication.This

applicationiscall“HelloWorld”anditwillrunonanAndroidVirtualDevice.

CreatenewAndroidapplicationprojectbyselectingon“StartanewAndroidStudio

project” from main Android Studio. Configure the new project by providing the

applicationnameas“HelloWorld”.EntryforCompanydomaincanbechosenbasedon

your domain URL or any string entry. This inputwill be used as the project package

name.Projectlocationentryiswheretheprojectfilewillbesavedinthecomputer.

Page 23: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

11

Pressnext to go tonextnewproject configuration.This configurationdetermines the

minimum SDK version that the application will support and run. Lower API number

meansmoredevicesthattheapplicationcansupport.

Press the Next button for choosing the type of Interface to begin with. There are a

numberofInterfacesbutfornowsettledwithEmptyActivity.

Page 24: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

12

Continuewiththenextbuttonforfurtherconfiguration.

TherearenomoreconfigurationsneededafterthisInterface.Pressthe“Finish”button

andwait.

Page 25: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

13

Theloadingprocesswilltakesometimesdependonhowgoodthecomputerhardware.

Oncetheconfigurationloadingprocesscompleted,afullAndroidStudioIDEwillshow

on the screen.Howevermore loading during this process until the loading bar at the

bottom right of the Android Studio had stopped and MainActivity.java file is finally

loadedwithoutanyerror.

ToruntheprojectsimplyselectstheMenuRunand“Run‘app’orpress“ShiftandF10”

atthesametime.Alternativelypressthegreenrightarrowbuttononthetaskbar.

Page 26: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

14

OR

Thefollowing“SelectDeploymentTarget”dialogwindowswillbedisplayed.Sincethere

is no Virtual device configure in the system, click on “Create New VirtualDevice”

button.

Select phone category and then from the list selectNexus S as device definition. This

selection isbasedon the lower specofdevices. If higher resolutiondevicesoptions is

selected more resources needed to run the virtual device thus lowering overall

performanceofcomputer.PressnextbuttontoselectSystemimage.

Page 27: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

15

Insystemimageoption,selectoneoftheavailableAndroidsystemimages.Ifnosystem

image available go ahead and download one from the download link. It may takes

sometimesduetothesizeofthesystemimage.

SelectsystemimagebasedontheversionofAndroidthattheapplicationisintendedto

run.Be aware that newAndroid version (API)will consumemore computermemory

andprocessorduetonewfeaturesprovidedbytheoperatingsystem.

PressnextbuttonandcompletethevirtualdeviceconfigurationbyprovidingAVDname.

ClickFinishbuttontocomplete

Page 28: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

16

ThenewAVDshouldappearinthedeploymenttargetwindow.SelecttheAVDandclick

onOKbutton.

Itmay takes some time to load the virtual device depend on the computer hardware

performance.Firsttimerunningthevirtualdevicewilltakelongertimeduetofirsttime

configurationoftheAndroidoperatingsystem.Onceloaded,theapplicationwillshowas

follow.AllfeaturesoftheselectedstockAndroidversionwillbeavailable.

Page 29: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

17

TheapplicationwillautomaticallyrunontheAVDwithasimpleHelloWorldtextappear

at the center of the screen. The application icon “Green Android” will also appear in

applicationlauncherapplicationlist.

The AVD behave exactly as normal Android operating systemwith standard features

provided by real Android phone. However certain hardware features such as sensor

value,camera,andlocationinformationprovidedthroughsimulateddata.Besurenotto

close theAVDonce it is running.Anynewapplication created can rundirectly to any

running AVD. Be aware that AVD consume significant size of resources thus making

computer running significantly slower.Alsomake sure theprocessorhyper‐threading

optionsisbeingturnonincomputermotherboardBIOSsystemtoutilizeHAXMfeatures

thatsignificantly improve theAVDperformance.Refer tothe following linkonhowto

enableHAXMonIntelbasedcomputer:

https://software.intel.com/en‐us/android/articles/installation‐instructions‐for‐intel‐

hardware‐accelerated‐execution‐manager‐windows

1.8 Getting to know Android Studio IDE 

BeforestartingwithdevelopingAndroidapplication it is important togettoknowthe

Androidstudioenvironmentfirst.AndroidstudioIDEinterfacedescribeinthefollowing

image.

Page 30: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

18

Sourcefromhttps://developer.android.com/studio/intro/index.html

Thefollowingaredescriptionforeachlabelfrom1to6.

1. Thetoolbarletsyoucarryoutawiderangeofactions,includingediting,debugging,

runningyourappandlaunchingAndroidtools.

2. Thenavigationbarhelpsyounavigatethroughyourprojectandopenfilesfor

editing.Itprovidesamorecompactviewofthestructurevisiblein

theProjectwindow.

3. Theeditorwindowiswhereyoucreateandmodifycode.Dependingonthe

currentfiletype,theeditorcanchange.Forexample,whenviewingalayoutfile,the

editordisplaystheLayoutEditor.

4. ThetoolwindowbarrunsaroundtheoutsideoftheIDEwindowandcontainsthe

buttonsthatallowyoutoexpandorcollapseindividualtoolwindows.

5. Thetoolwindowsgiveyouaccesstospecifictaskslikeprojectmanagement,

search,versioncontrol,andmore.Youcanexpandthemandcollapsethem.

Page 31: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

19

6. ThestatusbardisplaysthestatusofyourprojectandtheIDEitself,aswellasany

warningsormessages.

Androidstudioeditorisasmarteditorthatallowforquickcodecompletionwhereany

variables, methods, expression and so on automatically identified by the editor. The

editoralsoimplementscolourcodingandautoformattingforeasytoreadandcleaner

code.TherearemorefeaturesofAndroidStudioandforfurtherinformationpleasegoto

the Android Studio official website at the following link:

https://developer.android.com/studio/intro/index.html

1.9 Dissecting “Hello World” Project 

Understanding the basic premise of how Android programming works is important

beforegoingintomoredetails.WhenanewAndroidprojectiscreated,aseriesoffiles

and folderwill be automatically generated in theproject directory.Amongmany files

andfolderscreatedbyAndroidStudio,thereare2filesthatwillbeautomaticallyopen

each time in the editor screen (3). Both files are MainActivity.Java and

activity_main.xml(unlessthenamesofbothfileshavebeenchangedduringtheproject

definitionbefore).

ACVITITY_MAIN.XML 

This file is themain layout interface file inXML formatand canbeaccessed fromres

folder without subfolder layout. Android uses XML script to describe layout and its

component.Itisamarkuplanguagethatdefinesasetofrulesforencodingdocumentsin

a format which can be translated into graphical interface representation. Every

componentinapplicationinterfacerepresentedinitsownxmltags.Eachtagcontainsa

setofpropertiestagthatfurtherdefineshowthecomponentslookandbehave.Howthe

Page 32: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

20

componentportraysonlayoutsuchassize,text,colour,shapeandmanymorearedefine

ineachpredefinedtag.Thesepropertiescanbechangedusingpropertiesscreenorhard

codedinthexmlfileoreveninjavaprogrammingfiles.

1. Componentspalletwindow:Draganddropcomponentfromthispalletwindow

tolayout.

2. SelectingbetweenXMLandgraphicalmode.

3. Layout component name TextView that function to display text on the layout.

Thisisthedefaultcomponenttoappearforeverynewprojectcreated.

4. PropertieswindowthatdescribeallpropertiesofTextViewcomponent.

Page 33: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

21

For any new component dragged to the layout, a new tag entry will be inserted

automaticallyintotheXMLfile.ForexampletrytoaddabuttontothelayoutfromForm

Widgetpalletbydraggingthebuttontothescreen.Makesuretosavethefileforevery

newchangesintroducedtolayouttotakeeffect.

Anewxml entry tag startingwith “<Button” andendswith “/>”willbeadded. Inside

thistagisalistoftextpropertiesdescription.Eachtagdescribesthelookandfeelofthe

buttononthelayout.Thefollowingtabledescribesomeofthetags.

XMLTagproperties Description

Android:id="@+id/button1" Unique id that will refer through

MainActivity.java

Android:layout_width="wrap_content" Width of the button based on the

contentofthetext.

Android:layout_height="wrap_content" Height of the button based on the

contentofthetext.

Android:layout_alignLeft="@+id/TextView1" The button alignment left to

TextView1

Android:layout_below="@+id/TextView1" The button position below

TextView1

Android:layout_marginTop="36dp" Marginfromlayouttop

Android:text="Button" Textcontentofthebutton.

Morepropertiescanbeaddedlaterusingthepropertiessection.Eachpropertiescanbe

addedormodifythroughthisinterface.Howeversometimesnewpropertiesneedtobe

inserted manually through xml before it can be edited through properties interface.

Understanding more on properties of each layout component allow for better

customizationanduserinterfacedesign.Therewillbemoreonthistopiclater.

MainActivity.java 

Android uses Java based programming as its main programming language.

MainActivity.java file is the file that contains all Java programming that executes

instructioninthelayout.Anybuttonpressorinterfaceinteractionishandledbythisfile.

Page 34: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

22

package com.slumberjer.helloworld; //line 1

import android.support.v7.app.AppCompatActivity; //line 3

import android.os.Bundle; //line 4

public class MainActivity extends AppCompatActivity { //line 6 @Override //line 7 protected void onCreate(Bundle savedInstanceState) { //line 8 super.onCreate(savedInstanceState); //line 9 setContentView(R.layout.activity_main); //line 10 } line 11} //line 12

TheprogrammingislikeanyotherJavaprogrammingwhereitcontainsclassnameand

method.Line1basicallydefinepackagenamewheretheprojectnamehadbeengiven

duringthebeginningofprojectcreation.Packagenameisauniquenamethatrefersto

Android project and if any other classes require, the class package name can be

imported.Nextinline3and4,AndroidJavaprogrammingrequirestoimportofcertain

predefined classes that hadbeen use in the class body. Line 3 and line 4 define class

importsthatneededforthecurrentproject.Everynewcomponentthatneedsofcertain

classeswillbeimportedinthissection.

Line 6 defines themain classwhere class name shouldhave the samenamewith file

name(MainAcitivity.java).Themainclassalsoextend itclasswithAppCompatActivity

classwhichdefinetheimportofline3.Themainclassbodystart(line6)withanopen

curlybraces “ { “ and endwithclose curlybraces “ } ” at line12.Classbodycanonly

containvariabledeclarationandobjectdefinition.Anyoperationcodemustbeplacedin

methodbody.Itiscrucialtounderstandthisprogrammingbodystructureusingcurly‐

bracesasopenandclosebody.

Line8until11isthemainmethodindicatingby@Overrideannotation.Mainmethodis

where the program looks for instruction during first program execution. The above

onCreate()methodbasicallydescribetosetthecontentviewandruntheLayoutusing

activity_main.xml.Ifanyfuturecodesthatrequiredtoberunduringfirsttimeexecution

thisistheplacetodo.

Thenexttopicstartwillwithbasiclayoutcomponentandinteractionusingbothlayout

andmainclass.Afewotherconceptssuchasuserdefinedmethodandmoreonoverride

methodswillbeintroduced.

Page 35: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

23

TOPIC 2 2.0 BASIC COMPONENT PROGRAMMING 

This topicwill cover basic usage ofmost common layout component; textview,edit

textandbutton.This3layoutmembersarecommonlyuseinanyAndroidapplication

and should be enough to develop basic Android application. Each component will be

describedusingasimpleprojectexampleanddetaildescriptionwillbegivenonhowthe

codeworks.

Page 36: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

24

2.1 About Constraint Layout (IMPORTANT!!!) 

DuetotherecentupdatewiththeAndroidStudio,anynewprojectcreationwillalways

getconstrainlayoutasitsdefaultlayout.Constraintlayoutisanewtypeoflayoutthat

allow forcomponent/s in the layout toresizeandrepositionbasedon thescreensize

andorientation.Itisagoodlayoutduetoitsabilitytoadjusttodifferentandroidscreen

sizes.HowevertousethislayoutwillrequiresgoodknowledgeonhowAndroidlayout

interfaceworks and it canbequite tricky touse.The following figure showshow the

relativeconstrainshowsnothinglikethedesignwhentheapplicationisrunintheAVD.

Allcomponentsbecomescatteredallovertheinterfacewithoutproperhandlingofthe

“constraint”.

Linear layout is amuch easy layout to use andmanage for simple programwith few

inputsandoutput.Componentswillbearranged intoaseriesofverticalorhorizontal

orientation. Both orientations can be nested to allow components to be placed in

horizontalarrangement.

Touselinearlayout,accesstheLayoutspaletteandchooseLinearLayout(vertical).Drag

thelayoutcomponenttothecomponenttreeandthenaddanycomponenttothischild

linear layout. If any components thatneedahorizontalplacement just another layout

withintheintendedlayoutandaddcomponentinsidethatlayout.

Page 37: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

25

Theapplicationwillcontaintwolayoutsachildlayout(linearlayout)andparentlayout

(constrain layout). Although the parent layout could be changed to linear layout, the

usesofsuchlayoutdesignjusttomakesimplifyuserinterfacedesignforbasicAndroid

applicationdevelopment. Linearlayoutisgoodforsimpleinterfaceandshouldsuffice

for basic Android application development. However it is also recommended to learn

how to use Constrain Layout since due to the recent update, Constrain Layout has

becomethedefaultlayoutforAndroidStudio.

2.2 TextView, EditText, and Button 

Text view, EditText and Button are the 3most common components in any Android

programming.Thesecomponentswillbedescribeasdetailaspossiblesincetheusage

ofanyothercomponentsbasicallyusingthesameprinciple(Createobject,setobject

reference,anduseobjectmethod–moreonthislater).Forthosewhoarenewin

androidprogramming,trytounderstandtopic2.21.

2.2.1 Text View 

Textviewisalayoutcomponentusefordisplayingtextoutputoruseforlabellingother

component such as edit text. Text view can be accessed form widgets pallet on the

activity_main.xml graphical layout.Adda text view to the layout; drag the component

intothelinearlayout.DoubleclickwillrevealtheXMLtagfortextview.

Page 38: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

26

Default text view XML tag defines several basic properties such as unique id, width,

height, and text. Change the textproperties to any static textwill change the display

value on the layout. However the text can also dynamically change through

programming.

The followingprojectexampleallowusertochangethedefault textviewtextvalueto

anothervaluethroughprogramming.

Project 1‐ TextView 

Instructions:

a) Createanewprojectusingthemethodsdiscussin“HelloWorld”projectbefore.

Givetheprojectaname.

b) Addalinearlayouttotheconstraintlayout.

c) Add a text view to the linear layout by dragging fromWidget pallet and then

savethefile(ctrls–makethisasyourhabit.Veryimportant!).

d) OpenMainActivity.javaandadd the followingcodeafter line11as follow(red

box).

Page 39: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

27

e) Savethefile.

f) Trytoruntheproject.

Afewthingsshouldbenotedafterwritingthecode.Theprojectcannotexecutedueto

the error generated in theMainActivity.java. The editor show there are errors in the

codebyshowingredtextoverTextView(line12)andalsosetText(line13).Thisisdue

tothemissingclassandimportoftherequiredclassisneeded.

TheredtextTextViewisanerrorindicatorthatdescribesmissingaclassneededbythe

code.Therearethreewaystoimportthemissingclass.

The firstmethodbymoving the editor cursor to the corresponding text andpressing

alt+enterkeyat thesame time. Itwillauto importauto import therequiredclass.Be

careful when using this shortcut. Sometimes eclipse will import wrong class to the

project usesmore advanced classes that listing refers tomore than one class. Always

checkifthecorrectclasshasbeenimported.

Thesecondmethodisbyusingmouseover.PointthemousecursorovertheTextView

andaredlightbulbwillappear.ClickonthebulbandselectmenuImportclass.

Themissingclasswillbeautomaticallyinsertedintoimportsectionoftheclass.

ByimportingtheTextViewclass,errorinthetv1.setTextautomaticallyresolved.Thisis

duetothemethodsetTextbelongtotheclassTextView.

This istrueforallothercomponentsreferredinaprojectsuchatextedit,button,and

etc.Theprocessbasicallythesameanditisalsoworthmentioningthatforeveryobject

referring to amethodorobjectusing the “<object>.”dot, a seriesofmethods/options

willbepopupandselectforeasycodecompletion.

Page 40: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

28

FULLCODEFORPROJECT

MainActivity.java

activity_main.xml

Page 41: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

29

CodeDescriptionforMainActivity.java

Code description provide the fundamental understanding how Android programming

works.ThissectiondescribelinebylineforeachoftheMainAcitivity.javasothatreader

willhavesomeideahowtheflowofinstructionexecutionworks.Allothercomponents

workusingthesameprinciple.

Line 1 describe in MainActivity.java is the project package name. The package name

mustbeauniquenamesinceifdeveloperwanttouploadtoGooglePlayStorelater,this

package namewill be used as unique entry to the store. The name of the package is

automatically inserted in any new project creation. To change package name select

menu refactor then rename. All classes that within the same package name will be

rename.

Line 3 until 5 listed all the reference classes used in the project. This entry is also

automatically generated or inserted when new project/component imported into

project.Besuretoimportthecorrectclass.

Line7until16istheclassnameanditsbody.TheclassMainActivityisapublicclassand

itsnamewillalwayshasthesamenamewiththe filename(This ishow javaclass file

namingworks). This class further extend to a parent class called AppCompatActivity.

This class enablesupport forolderAndroiduser interfaceandallowing for consistent

GUIacrossdifferentAndroidversions.

Lines 9 to 15 within the MainActivity class describe an override method from

AppCompatActivity. Its override the method from its parent class and implement its

own instruction. The method name is onCreate with protected type where only

MainActivity class can access this method. This is the first method that run when

Androidapplicationstart its lifecycle.Themethodalsopassabundleobjectthatstore

currentlayoutactivitystatetothemethod.Inline11,themethodcallsitsuperclassto

runitsoriginalonCreatemethodandextendingthestateeverytimetheclass isrecall.

Line12thencallthelayoutanddisplayitonthescreen.R.layout.activity_mainrefersto

theresourcefolderwheretheXMLlayoutfileislocated.

To use any component added from the pallet to the layout, there are two basic code

instructions required. The first is object creation and reference and second one is

object method execution. Both are the fundamental of any object oriented

programmingparadigm.ThisprojectuseoneTextiewinthelayoutandthecreationand

executionoftheinstructiondescribeinline13andline14.

Page 42: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

30

|<Class>|object‐name|=|(Class)|method(Resource.id.<object‐layout‐id>)|;

Line13 instructionbasicallydescribes the firstprocesswhich isobject creation (tv1).

Thentheobjectmakesreferencetoselectedlayoutcomponentid(TextView1).Thetv1

objectnowwill inheritTextViewclassandcanuseall themethodsavailable fromthe

class.Anymethodapplytothisobjectwillreflectitsoperationoutcometothetextview

holding id of TextView1. Object declaration (TextView tv1) can be done as class

declarationorwithinmethoddependonhowtheobjectwillbeusedlater.Iftheobject

declaresintheclasslevel,allothermethodcanusethisobjectwithouthavingtodefine

theobjectineverymethodthatusesit.

object.methodname(“Passingparameter<String>”);

Line 14 on the other hand describes the second operation in layout manipulation

instruction.Anobjectthencanstartcallmethodsfromtheclassdefinitionitdoesbelong

to.AndroidStudioprovideeasyaccesstoallmethodsavailablebyjustputa“dot”right

aftertheobjectnameandinthiscaseistv1.Alistwithitspassingandreturnargument

forthemethodswillbeshown.

TheselectedmethodsetText()usesthepassingstringparameter(“MyNameisHanis”)

todisplaystatictextinTextView1.

SincebothcodearelocatedinsidetheonCreate()method,itwillexecuteonthefirstrun.

The output shows “My Name is Hanis” display on the screen. Of course there is no

Page 43: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

31

interactionwith the applicationyet since theonlyoperation in theproject is to show

simpletextonastaticlayout.

It is very important to really understand the concept of object creation‐reference

(TextView tv1 = (TextView) findViewById(R.id.TextView1); ) and object‐method

execution (tv1.setText("MyName isHanis");) . Every other layout component that

willbediscussedfurtherinthisbookwillusedthisbasicconceptonewayoranother.So

keepthisinmind!!!

3.2 Button 

Button is a handy layout component that allow user to interact with Android

application.TherearetwowaystoaccessbuttonoperationeitherthroughonClickxml

tagorbyusingbutton listener.This topicwill look into the simplestconceptbyusing

onClick xml reference from layout properties. The listener method will be described

later.

Project 2 ‐ Button 

Instruction:

a) CreateanewAndroidproject.

b) Addalinearlayouttotheconstraintlayout.

c) Addabuttontothelinearlayoutandsavetheproject.

d) Create the following “user defined” method inside the main class

(MainActivity.java).

Goback to the layoutanddouble clickon thebutton toaccessxmlbutton tag.

Addanewtag(android:onClick = “myMethod”)lineinsideasindicatedby

redboxandthensavethefile.Buttontagstartfrom<Button….andendwith/>.

Page 44: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

32

e) AddthefollowingmethodinMainActivityclass

f) RuntheprojectonAVDandpressthebutton.

FULLPROJECTCODE

MAINACTIVITY.JAVA

Page 45: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

33

ACTIVITY_MAIN.XML

Code Description 

Userdefinedmethodisamethodcreatedbyuser.Allinstructionswiththismethodcan

only be triggeredwhen a call is beingmade. Call can comes fromuser action such as

press,swipe,longpress,orfromothermethod.Thesimplestwaytocallauserdefined

methodusing button is bydirect referenceof themethodname throughXMLonClick

buttontag(refertostepd).Themethodheadershouldalsoprovideapassingparameter

with class‐object (View v) as shows in line 16. Make sure method written outside

onCreatemethodandwithintheclassbody.

Line 16‐18 from the MainActivity.java class refers to the user defined method with

passingobjectv(Viewv)fromViewclass.Methodbodystartfrom“{”andendswith“}”.

Everyinstructionwithinthiscurlybracketwillbeexecutedwhenthemethodiscalled.

Inside thismethod there is a simpleToast instruction thatwill pop‐up a text on the

screeninashorttimewhenthebuttonispress(refertostepf).

Page 46: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

34

Line19inactivity_main.xmlenabledthecallingofthemethod.Thenameofthemethod

mustremainthesamewiththenameofthemethoddefinedinMainActivity.java(down

touppercaseorlowercase).Ifthere’smistakeinmethodnameormissingthe(Viewv)

parameterofthemethod,thebuttonwillproduceerrorwhenpressed.

Thisisasimplewayofimplementingfeedbacktouseraction.Anyinstructionwiththis

method will be executed. Understanding this concept is very important since any

interactionwithuserisbasedonmethodcalls.

3.3 Understanding Toast 

Atoastprovidessimpletextfeedbackinatimebasedpopuptext.Mostofthetimetoast

isbeingusedtoprovideuserwithasimplemessageorresultfromparticularoperation.

Theusageisasfollow:

TouseToastjustwritea“Toast”instructionandapopupwillappear.Selectthesecond

menufromthepopupthatlabel“CreateanewToast”.

AcompleteToastdefinitionwillautomaticallyappear.Writeanytextinthe““quotation

toshowwhattexttoappearonscreen.Tochangehowlongthetoastwillappeartryto

change the LENGTH_SHORT to LENGTH_LONG option. Toast sometimes also use for

debuggingpurposesbymaking sure that themethodhasbeenaccessbyoperationor

showingorverifyingvalueofcertainparametercorrectlycalculated.Toast is indeeda

veryhandyclassthatcanbeusedformultiplepurposesandwillbeusedalotlater.

3.4 Text Fields 

TextFieldsisoneofthemostusedcomponentsinAndroidapplicationdevelopment.It

allowsforusertoinputdataandthentheapplicationcanfurtherprosesthedata.There

aredifferenttypesofTextFieldsdependingonapplicationusage.Therearetextfieldfor

standardusage,name,password, email, phone, address,multiline, time,date,number,

and etc. The difference between one another is that the input type that the text field

Page 47: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

35

acceptcertainvalueandthesoftkeyboardwilldisplaydifferenttypeofkeyboardwhen

selected. The android:inputType option enables application to select the type of

keyboardthatappearsonscreen.

TextfieldXMLtagstartwith<EditTextandendswith/>.Withinthebodytagcontainall

properties of the selected text field. Properties can be further add or edit using the

propertieswindowsorXMLediting.

SinceTextFieldshandledata inputfromuser, thevalueof thedatamustbeholdbya

variable thus theneed forunderstandinghowvariableholdsanddeclaredata type in

programmingisimportant.Thedatainputbyusercanbeinanytypeofdata.Handling

the data type is also critical formaintaining the data integrity. Text fields in Android

handlebyEditTextclass.

Project 3 – Text Fields 

a) Createanewproject.

b) Addalinearlayouttotheconstraintlayout.

c) Addaplaintextfromtextpalettetothelinearlayoutandsavetheproject.

d) Addabuttontothelayout.

e) InsertthefollowingmethodtotheMainActivity.java

Page 48: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

36

f) MakereferenceofmyMethodatothebuttononClickXMLtag.

g) Importall therelevantclass,runtheprojectonAVD.Enteranytext inthetext

fieldandpressthebutton.

Page 49: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

37

FULLPROJECTCODE

MainActivity.Java

Code Description 

Lines17to22describeuserdefinedmethodnamedmyMethoda.Themethodreturnsno

value(void)andpassinginterfaceClassobjectv.Thisisimportantforanymethodcall

fromtheonClick interface layout.Theobjectnamecanbeanythingbut itmustdefine

fromViewclass.Insidethismethodthereare3instructions;toreaduserinputfromtext

field(line18),toassignthevaluetoavariable(line19)andfinallytotoastbackthetext

to screen (line 20). Line 18 defined object ed1 created from class EditText with

referencestoeditText1fromlayoutid.Togetvaluefromtextfield,getText()methodis

use.Thevalueisthenstoredinvariablecalledname(line19).Line20finallythentoast

backthevaluestoredinvariablenametoscreen(line20).

Page 50: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

38

ACTIVITY_MAIN.XML

Code Description 

The layout contains an editText and a button with onClick properties set to method

myMethoda. Main layout (parent layout) is a constraint layout and child layout is a

linearlayout.

Some Useful “Trick” for EditText 

UserinputcanbefurthercontrolbysettingupinputType

Empty User Input Error 

Textutilsclassisusefulobjecttocheckifuserdidnotenteranyinputfortheedittext,

TextUtils object can be used to catch this error. Use this if statement to check before

Page 51: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

39

proceedswithvariableassignment.Theerrorwillappearwithintheselectededit text

andwouldveryhelpfulforuser.

public void myMethoda(View v){EditText ed1 = (EditText) findViewById(R.id.editText1);

if (TextUtils.isEmpty(ed1.getText())){

ed1.setError("Input data");

return;}

}

Page 52: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

40

TOPIC 3 

3.0 SIMPLE APPLICATION USING BASIC COMPONENT 

Intheprevioustopic,thereare3basiclayoutcomponentsthatarefrequentlybeinguse

in any Android application development. From these three basic components, a fully

functionalapplicationsolvingparticularproblemcanbedeveloped.Thistopicdescribes

fourfunctionalapplicationsthatcanbedevelopedusingjustthesecomponents.Further

in this topic, instruction of how to create a new project on Android Studio, inserting

linearlayouttoconstraintlayoutandalsohowtoaddcomponenttolayoutwillonlybe

providedwithsimpleinstruction.

Page 53: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

41

3.1 Simple Calculator 

Acalculatorisasimpleapplicationthatperformsbasicmathematicaloperationontwo

numbers. The application interface will have two inputs edittext for numbers and a

buttontoperformtheselectedmathematicaloperation.

Instruction 

a) CreateanewAndroidprojectandgiveitanameMyCalculator.

b) Deletethedefaulttextviewfromthelayout.

c) Insertalinearlayout(vertical)intoconstraintlayout.

d) Addtwoedittext(number)inthelinearlayoutrightdowntoeachother.

e) Undertheedittext,addonebuttonfortheoperation.Changethebuttontextto

“+”.

f) Addonetextviewunderthebuttonfortheoutput.Changethetexttoresult.

g) AddthefollowingmethodtoMainActivity.Makesuretoputthismethodoutside

fromthemainmethodbutstillwithinclass.

h) AddthemethodtobuttononClickreferenceinactivity_main.

Page 54: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

42

i) Importalltherelevantclasses(alt‐enter)andruntheproject.

j) FinallyruntheprojectonAndroidEmulatororrealdevice.

FULLCODE:MAINACTIVITY.JAVA

Page 55: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

43

Code description 

Themainacitivity class above contain twomethods. The first one is onCreatemethod

where it define the “startup” script that execute when the application first run. The

secondmethodisauserdefinedmethodcalledaddOperation(line17‐27).Thecallcan

onlybeinitiatedbythebuttononClickproperties.Themethodstartswithdeclarationof

edittextobjects (ed1, anded2)and to their respected references from layout id.Then

twovariablestypeinteger(num1andnum2)hasbeendefined. andthenreceivetheir

valuefrombothtextfieldobjectsthroughgetText()method.Howeverbothvaluesneed

tobe converted to integer typebefore anymathematicaloperation can takeplace.To

convertavaluefromstringtointeger(number),classIntegerwithmethodparseInteger

isuse(line21and22).Bothvariablesthenprocessinline23withsimpleaddoperation

andthentheresult thenstore invariableresult.Finally line25definetv1object from

TextView class with reference to TextView1 and then show the result using setText

method(line26).

Assignment: Add 3 more basic arithmetic operations such as subtraction,

multiplication,anddivision.

Tips:create3moreadditionalmethodsandbuttons.

3.2 BMI Calculator 

ThesecondprojectiscallBMIcalculator.Itbasicallyusestocalculatebodymassindex

thatusefulindetermininguserweightstatus.Inthisapplicationuserwillneedtoinput

theirweightandheightand theapplicationwilluse thesedata tocalculateBMI index

using special formula. The following is the formula to calculate BMI.Weight is in kg

dividedbyheightinmetermultiplyby2.

Instructions 

a) CreateanewprojectcalledBMIcalculator.

b) Deletethedefaulttextviewfromthelayout.

c) Insertalinearlayout(vertical)intoconstraintlayout.

Page 56: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

44

d) Add the followingcomponent; textview(4), text field (2),andbutton(1)with

theirrelevanttextsasfollows:

e) AddthefollowingmethodinyourMainActivity.javaclass

f) MakeareferenceofthemethodtobuttononClickinactivity_main.xml.

g) Importallrelevantclasses(ctrl+shift+o)andruntheproject.

Page 57: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

45

h) TheBMIvaluedecimalpointiswaytoolongandunnecessary.Thevaluecanbe

formattedto2decimalbymodifyingsetTexttv1object.

FULLCODE:MAINACTIVITY.JAVA

Themethod that uses to calculate BMI is calculateBMI starting from line 17 until 26.

Basicallytheoperationisthesamewiththefirstexamplewhichtakingthevaluefrom

Page 58: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

46

the interface and perform some operation to the value and return the result to the

layout.Line23showshowtotranslatetheformulaintoinstruction.

Assignment: Add additional TextView to show information regarding BMI categories

basedonthefollowinginformation:

Useconditionalstatementtocompletethisassignment.Eg:

“If else” statement allow program to make selection based on predetermined

conditions. In the above example, the condition check the value of BMI less than

18.5anythingwithin thecurlybracketblockwillbeexecuted.Thesecond“else if”

checkiftheBMIvaluewithinrangebyusing&&(AND)logic.Bothstatementsmust

betruebeforetheoperationcodecontinue.

3.3 Fun with Name 

In this project, user will be requested to input their name and then when press the

button,asimpleanalysisoftheirnamewillappear.ThisprojectusessomeStringclass

methodssuchaslengthandreversemethod.

Instructions 

a) Createanewproject(NameAnalysis)

b) Changedefaultlayoutinterfacetolinearlayoutverticalandaddtextviews,text

fieldsandbuttonasthefollowinglayout.

Page 59: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

47

c) AddthefollowingmethodtoMainActivity.Java.Java.

d) ReferthismethodtobuttononClickonlayout.

e) Save,importalltherelevantclasses(ctrl+shift+o)andruntheprojectonAVD.

Code Description  

Thecodedescriptionusesnippetcodefrominstructioninc.Line21describetheobject

(buffer)derived fromStringBuffer class.This class allow for stringmanipulationwith

moremethodssuchasappend, reverse, substringandetc. Substringmethodallow for

extraction text from the string variable. String variable can also provide additional

methodsuchaslengththatreturnsthecharacterlengthforthevariable.Lines25to28

describetheuseoftextviewwithnewlinemanipulator(“\n”).Textviewcanalsoshow

multiplevariableusingthe+<variable_name>code.

Page 60: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

48

3.4 Completing Simple Calculator 

In the previous project example, there are 3 important component namely text view,

text edit and button describe extensively. Basic method and method calling through

onClick XML tag had also been introduced. It also uses the concept of variable and

convertingstringvaluetonumbertype.

Inthisprojectexample,conceptsuchassharedvariable,parent‐childwillbeintroduced.

This project is a continuity from previous calculator project but with all the basic

calculator functions(add,subtract,device,multiply).Although it seemsrepetitive, this

topic is important indemonstrate theobjectandvariabledeclaredasglobal inaclass

andaccessfrommultiplemethods.

Instructions 

a) Createanewproject(FullCalculator)

b) Designthefollowinglayout

In this project, notice that the main layout is Linear Layout (vertical) style and

contain4otherlinearlayouts(horizontal).Thisisparent‐childlayoutswhichallow

the interface toplacechild layoutcomponent insidemain layout. Insideeachchild

linear layout (horizontal) contain twoormore components arranged sideby side.

The child layout is available under layout pallete. The placement of component

inside child layout can be put to center by adding Android:gravity=”center”

propertiestotherespectedlayout.

Page 61: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

49

c) Definethefollowingobjectandvariableunderclass

d) Addthefollowingmethodtothemainclass

Assignthismethodthefirstbutton“+”.

e) Create more of the same method operation for each button operations. Only

difference is the method name and the calculation operation. Assign each

methodtotheirrespectedbuttononClickXML.

f) Runtheproject.

Code Description 

Inthisprojectexampletherearetwoconceptsthathavebeenintroduced.Thefirstone

isdeclaringobjectandvariableaspublicwhereallothermethodscanuse.Theobject

declaredunderclassandnotinsidemethodcanbeusedinmultiplemethodsingeneral

(instructionc).There’snoneedtodeclareobjectorvariableagaineachtimetouseitin

anymethod.Thecodeismuchmoresimplifiedandmakestheobject/variableaccessible

through‐outtheproject.

In instruction d,method can now use objects and variables andmake the references

withouttheneedtodeclaretheirclassortype.Thevalueholdbyobjectorvariablealso

can be shared using this concept. Although the method can be further simplified by

Page 62: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

50

usingonlyonemethodonly,butthepurposeofthisprojectistoshowtheuseofglobally

declareobjectandasimplewaytouseit.

Secondconceptisinthelayoutdesignwhereitshowsadditionalapproachofusingsub

layout to control placement of component. Linear layout provides two type of

arrangement either vertical or horizontal. The arrangement can be mixed up allow

componenttosideway.

Page 63: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

51

TOPIC 4 

4.0 COMMON ERROR IN ANDROID STUDIO PROGRAMMING 

Thisisveryimportanttopictounderstandwheresometimeserrorcomeoutofnowhere

during project development even it shows no error in the programming. Some error

mightbecommonthantheotherandknownsolutionscanbeusedtosolvetheproblem.

Page 64: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

52

4.1 Unfortunately app has stopped 

This error is a common error formissing object references ormistake in defining an

objectreferencedtothewrongclassandcomponent.Forexampleinthefollowingcode

fragment,anobjecthasbeendeclared(line7)andused(line13)butnoreferencehas

beenmadetocomponentonlayout.

Themissingreferenceshouldbeinsertedintoline13beforetheobjectcanbeused.

Thiserroralsocanalsocomefrommistakeindefiningclassobjecttype.Forexamplethe

objecttv1shoulddeclareTextViewasitsclassinsteadEditText.Sincethereference(line

15)referstoobjectTextView1fromlayout.

Page 65: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

53

4.2 Infamous R. error 

This type of error comes from resource error where the project suddenly imports

Android.R. ImportingAndroid.Risusuallynot intentional; itsometimeshappenswhen

anIDEasktoautomaticallyaddimportsatatimewhenproject'sRclassitnotpresent.

Oncetheimportisthere,alotof"confusing"errormessages(line13and14)willshow

upbecauseofthefieldsavailableonAndroid.Rarenottheonesexpectfromjustlooking

atRclass.Deletingthisimportnormallywillrestorebackanyerrorproducebyit.

Thismistake cause by error anywhere within the resource (res) folders. Most of the

time,itiserrorinlayoutfileorxmlfileswhereXMLtagpropertiesmisspellormissing

certaincode.Theuseofinvalidgraphicnameinthedrawablefolderalsocancausethis

problem. The file name in this folder shouldn’t start with number or use any capital

letteroralsowhitespaceinfilenames.Sometimesrestartingeclipsecanalsoclearthe

error.Ifnospecificerrorfound,trytocleantheprojectusingmenuProject/Clean.This

willrefreshprojectstructureanditslibraries.

4.3 Component Id not available 

Most of the error relating component id not available is because of the error in the

layoutXMLfile.Theidisnotrecognizingbytheclasssincethelayoutfilecontainerror.

Fixingtheerror(i.e.missingormistakeintagdefinition)shouldrecovertheerror.

Page 66: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

54

4.4 Using the Log utilities 

Logisapowerfultooltocheckforanyruntimeerror,variablevalue,orjustmakingsure

thecodecorrectlyexecutetheinstructionsequence.Uselogasfollow:

There are two passing parameter in the Log. The first one (TEST) is for the tag

identification and the second parameter is the part (variable/string) thatwewant to

check.

LogresultcanbeobtainedfromLogCattabatthebottomofStudioIDE.Searchforthe

TagthathasbeensetintheLogparameter.

Page 67: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

55

4.5 Exception Error Catch 

Mostof the error canbe catchusingerror try‐catchblock. The followingareexample

howtousetry‐catchblock(redbox).Theblueboxiswherethecodethatweassumewill

produceerror.Ifthereareanyerror,thelogwithcatchandshowinthelogcatwindow.

Theprogramwillnotexitusingtry‐catchblock.

Page 68: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

56

TOPIC 5 

5.0 OTHER LAYOUT COMPONENTS 

ThefirstandsecondpartshouldprovidewiththebasicideahowAndroidprogramming

works. Concept such asmethod creation and call, object definition and reference and

layoutdesignhasbeen introduced. This topicwill furtherexplorehowtherestof the

layoutcomponentsuchastogglebutton,radiobutton,checkedbox,spinner,andswitch

functions. The notion remains the same and only applies using different classes and

methods. The following examples shows only snipped code unless it is necessary to

showfullcodes.

Page 69: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

57

5.1 Toggle button  

Toggle button is a button with two states either on or off. This button provide

applicationwhichrequiresonebuttonthatperformtwodistinctoperationsdependson

itstate.

Instruction 

a) Createanewproject.

b) Addonetogglebuttontoyourlayout.

c) AddthefollowingmethodinyourMainActivity.Java

1. public void myToggleButton(View v){2. ToggleButton toggle = (ToggleButton) 3. findViewById(R.id.toggleButton1);4. if (toggle.isChecked()== true){5. Toast.makeText(getApplicationContext(), "Button 6. is on", Toast.LENGTH_SHORT).show();7. }else{8. Toast.makeText(getApplicationContext(), "Button 9. is off", Toast.LENGTH_SHORT).show();10. }

11.  }

d) CallthemethodfromtogglebuttononClickxml

e) Runtheproject.

Page 70: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

58

Method Description 

Thismethodhandle“on‐off”toggletogetthestatusofthebuttonoperation.Theuseof

“ifelse”statementblockisusetocheckthebuttonstatusisCheckedornot(line4).Ifthe

buttonispressedto“on”thenthestatusistrue.Otherthanthatthebuttonisoff(line7).

Anyfurtheruseroperationshouldbeinline5and8forthebuttonisonconditionand

line23and24ifthebuttonisoff.

5.2 Check Box 

Checkbox is another layout component that enable user tomark an itemormultiple

itemsatthesametime.Themethodusealsothesamewithtogglebuttonusingthe“if

statementblock”forselection.

Instruction 

a) Createanewproject

b) Addonetogglebuttontoyourlayout

c) AddthefollowingmethodinyourMainActivity.Java

Page 71: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

59

d) CallthemethodfromtogglebuttononClickxml

e) Runtheproject

Code Description 

The method myCheckMethod uses object (cb1) to get the status of the check box

operation(line18).Theuseof“ifstatement”istocheckthecheckboxstatusisChecked

ornot(line19).Ifthecheckboxisselectedthentheitemselectstatusistrue.Otherthan

that the check box select status is false (line 22). Further operation can be added

betweenbothstatusinthe“ifstatement”block.

Page 72: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

60

5.3 Radio Button with RadioGroup 

Radiobuttonisanotherlayoutcomponentuseinlayoutallowingusertoselectanitem

fromagroupofoptions.Radiobuttonusuallyuseinagroupandonlyoneitemcanbe

selected.RadiobuttonshouldonlybeuseinacontainerRadioGroupthatcanbeselected

fromContainersPalette.ThenaddradiobuttontotheRadioGroupcontainer.

Instruction 

a) Createanewproject.

b) Addtworadiobuttontolayout

Normally radio button would require more than one to be useful in any

application.Howeverradiobuttonneedtoputingroupsothatatanyparticular

time only one button can be checked. To do this select both radio button and

rightclick. Select “Warp inContainer”andselect container type from thedrop

downmenutoRadioGroup.

The container should have a unique layout id. From the outlinewindow, both

radio buttons under rg1 container. However a predefined radio group

componentcanalsobeusedfromformwidget.

Page 73: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

61

c) AddthefollowingmethodinMainActivity.Java

public void myRadioMethod(View v){

RadioButton rb1 = (RadioButton) findViewById(R.id.radioButton);

RadioButton rb2 = (RadioButton) findViewById(R.id.radioButton2);

if (rb1.isChecked()){

Toast.makeText(this, "One is check", Toast.LENGTH_SHORT).show();

}

if (rb2.isChecked()){

Toast.makeText(this, "Two is check", Toast.LENGTH_SHORT).show();

}}

d) AssignbothradiobuttonsonClicktomyRadioMethod.

e) Importalltherelevantclassesandruntheproject.

Method Description 

myRadioMethodmethod use two objects (cb1 and cb2) to get the status of the radio

buttonoperation. The“ifstatement” isusedtocheckbothof theradiobuttonsobject

statuseitheritisisCheckedornot.Ifthebuttonisselectedthenthestatusistrue.Other

thanthatnothinghappentotheradiobutton.Furtheroperationcanextendtheuseof

togglebuttonthroughifstatement.

Page 74: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

62

5.4 Spinner 

Spinner allowuser to select item fromdrop down style list. In this example a simple

spinnerwithstaticitemlistandabuttonforgettingtheinputselectedfromthespinner.

Instruction 

a) Createanewproject.

b) Addaspinnerandabuttontothelayoutpreferablyinalinearlayout.

c) To populate spinnerwith data, string array list is required. To create a static

array list, access folder res/values/strings.xml and open the file. Add a new

stringarraynamestateswithalltheitems.

d) To populate spinner with array, simply set the spinner entries to the array

element.

Page 75: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

63

e) AddthefollowingmethodtoActivityMain.javaclass

f) ReferthismethodtobuttononClickxml.

g) Importalltherelevantclassesandruntheproject.

Code Description 

Thespinnerexampleaboveusesstringarraytopopulateitsdatainthepulldownmenu

style. String array is an array of string items written in /res/values/string.xml. The

methoddescribeabovesimplyusetodefinethespinnerobject(line21)andgettheitem

from the spinnerobject by calling getSelectedItem()method. Finally a simple toast of

theselecteditemwillappearasdescribeinline23.

Page 76: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

64

Stringarrayfilesunderres/valuesfolder.

Thestringarraydefinedinstrings.xml.

5.5 Switch 

Switchisanotherlayoutcomponentthatallowusertoselectbetweentwostates;onand

off. The basic operation is also the samewith toggle button. Switch component only

availableinsdkAPI14andabove.APIlevel14andaboveisneededduringnewproject

creation.

Instruction 

a) Createanewproject

b) Addoneswitchtoyourlayout

c) AddthefollowingmethodinyourMainActivity.Java

Page 77: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

65

d) CallthemethodfromswitchbuttononClickxml

e) Runtheproject

Code Description 

Switch is another component provided by Android studio that allow user to select

betweentwostates.Thisexampleusesasimpleviewmethodcalledfromswitchbutton

onclick.Thestatusofeachstatesderived fromobjectcreated from line22 (sw1).The

useof“ifstatement”istochecktheswitchstatusisCheckedornot(line23).Iftheswitch

isselectedthentheswitchvalueturntoON.Otherthanthattheswitchselectstatusis

false (OFF) (line22). Further extend theuseof switchbutton through if statement to

implementanyotheroperationbasedontheconditions.

5.6 ListView 

Another useful component is Listview. Listview allow application to populate data or

custom interface in the list order. This is quite powerful tools if use properly. For

examplemostofpopularmessengerapplications(whatsup,viber,imoetc)useslistview

inlistingalltheirmessagethreads.ListviewavailableunderContainersgrouppallete.

Page 78: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

66

Instruction 

1) Createanewproject.

2) Addalistviewcomponentfromcontainerpalletetoapplicationlayout.

3) WritethefollowingcodeinsideonCreatemethodinMainActivity.java

4) Importallrelevantclassesandruntheproject

Page 79: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

67

Description 

TopopulatelistviewwithdatahastobeinonCreatemethodsincewewantthe

datatoloadwhenthelayoutappear.Touselistviewitisimportanttodefineits

object first. Line 22 define object for listview component (lv). Data for the

listviewisstoredinStringarrayasdescribeinLine23.Line25createobjectfor

theadapterofthelistview.Thenextlinethensetlistviewobjecttotheadapter.

Finallyline30to39implementonitemclick listenerfor listviewwhereitallow

clickactiononthelistwhenuserclickoneoftheitem.

Itemsinthelistviewaboveexampleareastaticlistandcannotdynamicallyadd

orremove.Toadditemtolistviewthroughprogrammingmodifythecodeabove

withthefollowing:

a. Declarethefollowingobjectinsideclass:

b. Leavethelvobjectcreation,adapterdefinitionintheonCreatemethod.

c. Donotchangeanythingtothelistener.

d. Add an EditText and a button to the Layout. Add the following method

additeminMainActivityandmakereferencetobuttononClickxml:

e. Run the project again and add content to the listview using edittext and

button.

Page 80: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

68

Dynamiclistviewitemaddatruntimeusingbuttonandedittext.

ListviewisaveryimportantUIcomponentthatneedmorepractice.Itisaverypowerful

componentparticularlyindatabaseapplicationorcustomlayout.Itcanfurtherenhance

withcustominterfaceforeachiteminthelayout,multicolumndatabaseentryandmany

more.UnderstandinglistviewopenupalotofpossibilitiesinAndroid.

Page 81: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

69

TOPIC 6 

6.0 UNDERSTANDING LISTENER 

IntheprevioustopicmostofthebasiccomponentsinUIlayout,suchaseditext,button,

radiobutton,togglebuttonandetc.howtocreateobjectanddothereferenceandalso

how to create method and called the method from onClick xml properties has been

discussed.MostoftheoperationsofarisbasedonsimpleonClickfunctionwhereuser

performclickontheselectedcomponent.

Thistopicwillexpanduserinputexperiencebyusinglistener.Forexampleabuttoncan

perform two functions at the same time with extending listener with long click

operation. Short click perform one operation and the long click can perform other

operation.Thiscanbedonebyusingthelistenerextendingthebuttonoperation.

Page 82: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

70

6.1 Button onClickListener 

The XML layout onclickmethod that described in earlier topic is basically hardcoded

withinlayoutxml.Thistopicwilllookintosecondroutinetoexecutemethodbyusinga

listener. This example will use two type of listener; onclick and onlongclick. Most of

layoutcomponentcanimplementthesetwomethodsorevenuseothertypeoflistener

defineintheirclasses.

Instruction 

a) Createanewproject.

b) Addonebuttontolayout.

c) Addthefollowinglistenerobject(btnClick)inMainActivity.java

Thismustbedoneoutsideofanymethod,amethodonitsown;alistenerobjects

insideclassbody.

d) Objectlistenerthenneedtoberegisteredwithanyobjectthatwouldliketouse

itoperation.Toregisterthisobject listener,buttonobjectmustbedefinedfirst

from onCreate method. Define the button object and finally call the listener

objectusingthebuttonobject(line17)usingthesetOnClickListener(btnClick)

e) Runtheproject.

Page 83: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

71

MAINACTIVITY.JAVA

  Code Description 

Implementing listener object allow application to dynamically change its

behaviour.Abuttoncanchangebehaviourusingmultiplesetofobject listener

and no longer bound to method defined in onClick. Implementing

onClickListener class addingmore control over button operations. The button

canberepurposed fordifferentoperationusingdifferentmethodcomparedto

staticreferenceusingonClicklayoutXML.

Line25inMainActivity.javadescribesthebuttonobjectcreationandreference

to button id button. As opposed to onClick XML reference which require no

buttonobjectreference.Line29createanobjectlisteneronclickandimplement

itwithoverrideonClickmethod(line31).Finallythebuttonobjectregistersto

thelistenerobjectwithsetOnClickListenermethodfromonCreatemethod(line

26).AnybuttonoperationwillbeintheonClickmethodimplementbylistener.

6.2 Button onLongClick Listener 

The onlongclick method is another listener object that allow for more extended

operations for any components. It allow for component to do operation when user

perform long touch. The process basically the samewith onClickListerner having the

Page 84: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

72

creation of object for the onLongClick and refer the button listener to the object.

HoweveronLongClickListenercannotbeimplementedusingtheXMLlayoutonClick.

Instruction 

a) Extendfromthepreviousproject.

b) Addthefollowinglistenerobject(btnLongClick)inMainActivity.javaclassbody

This must be done outside any method, like a method on its own; a listener

objectswithinclassbody.

c) To register this listener object, the button object must be first defined from

onCreate method. Define the button object and finally call the listener object

usingthebuttonobject(line18)usingthesetOnLongClickListener(btnClick)

d) RuntheprojectandpressbuttonalittlebitlongertoseethetexttoastforLong

Click.

Page 85: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

73

6.3 Implementing Listener within onCreate 

Another way of implementing listener is within onCreate method. The following

implementationhastobeintheonCreatemethod:

Using this technique, each button will implement its own listener. However such

implementation is quitemessy since all implementation is in onCreatemethod and it

canbeoverwhelmifmorethanonelistenerimplemented.

6.4 Implementing Listener on class 

Listener can also be implemented by its own class. The following code fragment

describeshowtodoit.Theclassimplementsandroid.view.View.OnClickListener.

TheClassnamewith turnerrorwhen it implementsOnClickListerner.Hoverover the

“error” class name and add unimplemented method from the popup screen. The

followingclasswillbeaddedautomaticallytotheMainActivity.javaclassbody.

AddanyoperationwithintheoverridemethodonClick.Thenaddabuttononthelayout

andmake object reference to the button inside onCreatemethod. Finally register the

buttontheclasslistenerusingsetOnClickListener(this).

Page 86: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

74

Dealingwithmultiplebuttonsusingthismethodrequiresthefollowingimplementation.

Useviewobjecttoaccessbuttonid.

Page 87: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

75

TOPIC 7 

7.0 LAYOUT MANAGER 

Designingofagood layout isvery important inanyAndroidapplication.Handling the

mobiledevicesmalluserinterfaceandmakingsureuserhadgoodexperienceusingthe

application is critical. Understanding how the application interface layout is being

handledanddealingwithmultiplescreensizesandresolutions.Androidlayoutcontrol

byViewclassthathandlesthewaycomponentsappearonthescreen.Anythingthatisa

View(or inherits fromView)canbeachildofa layout.Allof the layouts inherit from

ViewGroup (which inherits fromView).Multiple layoutcanalsobenested inorder to

providemorecontrolthewaythecomponentsisbeingarrange.

Page 88: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

76

7.1 Type of Layout 

This topic will be looking into several view layouts available in an Android mobile

application.Therearesixmainlayouts(notlimitedto):

o ConstraintLayout

o LinearLayout(horizontalandvertical)

o RelativeLayout

o AbsoluteLayout

o TableLayout

o GridView

o TabLayout

o ListView

Android studio allows developer to create layouts using XML file. All the layouts are

placedwithin /res/layout folder. Thedefault name for the layout is activity_main.xml

correspondingtoitsjavafileMainActivity.java.

7.1.1 Constraint Layout 

Thedefaultlayoutasforthelatestupdateissettoconstraintlayoutfromtheprevious

defaultrelativelayout.Constraintlayoutaddadditionalcontrolovercomponentwhere

itsetconstraintvalueforeachsideacomponenthadrelativetoscreenborder.

Page 89: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

77

However,theuseofconstraintisstillquitedifficultthesameasrelativelayoutwhereit

needscarefulhandlingofthecomponentitrelatedandconstraintto.Anymishapinthe

componentwillcausetheentireinterfacetoscramblealloverplaces.Constraintlayout

isstillquitenewandyettobeexplored.

7.1.2 Linear Layout 

In a linear layout, as the name suggests, all the elements are displayed in a linear

structure (below is anexampleof the linear layouts), eitherHorizontallyorVertically

and this behaviour is set in Android:orientation which is one of the attribute of the

LinearLayout. Layout can also sub each other from the parent layout. To enable

component arrange to the right; add linear layout horizontal and add component

(buttonsintothissublayout–seeoutline).

More precise control can be provided using option such as weightsum and

layout_weight.Layoutoptionweightsumallowfortheinterfacetoautomaticallyredraw

its component in relation to the screen size automatically. All components with its

parent defineweightsumwill be adjusted properly based on distribution set through

layout_weightforeachcomponents.

Linearlayoutwilltakesometimestoproperlysetduetoitsrigidnatureofplacingitem

in linear structure. However, components places in this layout will behave more

consistentlyandmucheasiertomanage.Anyapplicationthatrequiremorecomponents

andwould liketostayviewable insmallscreen interfacecanusescrollviewas layout

viewparent.Thiswouldallowtheinterfacetobescrollableonasmallscreeninterface.

Page 90: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

78

7.1.3 Relative Layout 

Inrelative layout,everyelementarranges itself relative tootherelementsor aparent

element.Asforexample,let’sconsiderthelayoutdefinedbelow.The“Cancel”buttonis

placed relatively, to the right of the “Login” button. Here is the code snippet that

achievesthementionedalignment(describebyredboxinXMLtag).Placementsofeach

componentarerelativetoeachothercomponent.

RelativelayoutusedtobethedefaultlayoutforAndroidstudiobeforebeingreplacedby

constraint layout.However,theuseofrelativelayoutisstillquitehardtodoandneed

more careful attentiondue to its “relative”nature.Any adjustment toone component

will affect other component placement that it’s related to. In complex interface this

couldturn interface intoamess.Userelative layoutcarefullyandplanallcomponents

placementinadvanced.

7.1.4 Table Layout 

TablelayoutsinAndroidworksinthesamewayasHTMLtablelayoutsworks.Itdivides

layoutsintorowsandcolumns.Theimageoutlinebelowshouldprovidesomeideahow

tabletlayoutarranged.ThefirstrowcontainonlyoneTextViewanditoccupythewhole

table. The second row contains 3 TextView and the row divided equally for each

TextView. The last row contains only two TextView and basically divided equally for

both.

Page 91: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

79

7.1.5 Absolute Layout (not recommended) 

This layout isbasedonthesimple ideaofplacingeachcontrolatanabsoluteposition.

You specify the exact x and y coordinates on the screen for each control. This is not

recommendedformostUIdevelopment(infactAbsoluteLayoutiscurrentlydeprecated)

sinceabsolutelypositioningeveryelementonthescreenmakesaninflexibleUIthatis

muchmoredifficulttomaintain.Considerwhathappensifacontrolneedstobeadded

totheUI.Youwouldhavetochangethepositionofeverysingleelementthatisshifted

bythenewcontrol.

7.1.6 Frame Layout 

FrameLayout is designed to display a single item at a time. You can have multiple

elementswithinaFrameLayoutbut eachelementwill bepositionedbasedon the top

leftofthescreen.Elementsthatoverlapwillbedisplayedoverlapping.FrameLayoutcan

becomemore usefulwhen elements are hidden and displayed programmatically. You

canusetheattributeAndroid:visibilityintheXMLtohidespecificelements.Youcancall

setVisibility from thecode toaccomplish thesame thing.The threeavailablevisibility

valuesarevisible,invisible(doesnotdisplay,butstilltakesupspaceinthelayout),and

gone(doesnotdisplay,anddoesnottakespaceinthelayout).

7.1.7 Listview Layout 

Listviewisatypeofcomponentorviewthatallowitemtolistdowninverticalmanner

and also scrollable. Listview can also implement as an interface component that

availablefromcompositepallet.

Page 92: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

80

In this exampleproject, listview is implemented as layout viewwhere it occupies the

entirelayoutasliststructure.

Instruction 

a) Createanewproject.

b) Changeyouractivity_main.xmltothefollowing:

Noticed that the activity_main.xml layout file areno longer asusual layout

file. The xml only contain one TextView definition. Since the project no

longerextendactivity,activity_main.xmllayoutnolongerneeded.

c) UpdateMainActivity.javawiththefollowingcode.Lookintocodeshighlight

intheredbox.Importalltherelevantclass.

Page 93: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

81

The class extends to ListActivity indicate that the layout is no longer as

standardActivity(line13).Listviewactivity(activity_main)iscalledthrough

arrayadapterpopulatedusingarraySTATESdatadefinedin14.Line26to33

definesthelistenerforthelistview.

d) Importalltherelevantclassesandruntheproject.

Thewholelayoutimplementslistviewasitslayout.Eachentryinthearrayis

listedinthelistview.Listviewlayoutitemalsorespondedtoclickeventand

showtoastforeachiteminlist.

Page 94: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

82

7.8 Custom Listview 

Listviewlayoutisaveryusefulmethodofdisplayinglistofitemorrepeatinginterfaces.

Basiclistviewcanbefurtherextendedbyusinglayoutcustom.Incustomlistviewmore

complexinterfacecanbefurtherdeveloped.

Instruction 

1) Continuefromthepreviousproject.

2) Update main layout xml and set parent layout with an imageview and a

TextView

3) Create another Java file and name the file CustomAdapter with the following

code:

Page 95: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

83

Customadapter classuse in thisproject is to control layout thatwill appear in

the list.Each listwill enclose thiscustomlayout.Twocomponentsavailable in

the layout; an imageview and TextView received data from the main class to

showrespectedentryfromstringarray.

4) UpdateMainActivity.javawiththefollowingcodes

5) Downloadaseriesofimagesandputthefilesintores\drawabledirectory

Makesuretheimagefilenameonlycontainsmallletteralphabetonly.

Page 96: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

84

6) Runtheproject

7.1.9 Simple Tab Layout 

Tab layout isaveryhandy layoutusedbymanypopularAndroidapplicationssuchas

Whatsup, FacebookMessenger, Telegram and etc. It enablesmultiple interface access

throughtabbedlayout.

Instruction  

a) Createanewproject

b) Changelayoutinactivity_main.xmlwiththefollowingoutline

Page 97: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

85

Followthelayoutexactlyasfollow:

c) Create3additionallayoutwithstandardlayout

d) Create3additionalJavafilethatrepresentforeachtabrespectively

Makesureeachfilesetitcontenttoeachlayout.

Page 98: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

86

e) AddthefollowingcodetoMainActivity.Java

f) Registereachtabactivityintomanifest

g) Importalltherelevantclassesandruntheproject.

Page 99: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

87

7.2 Supporting Different Screen Size 

Android operating system runs on multiple screen sizes from the smallest on smart

watch, on phone, on tablet and also on smart television. Various screen sizes poses

difficultchallengesindesigningapplicationinterfacesincetheappcomponentneedto

adapttoscreensizechanges.

7.2.1 Use wrap_content and match_parent 

The size of every components determine by layout_width and layout_height. The size

can be set using values. Consider the following interface layout. The parent layout is

linearlayout(vertical)withtwochildsalinearlayout(horizontal)andabutton.Within

the child layout there are two components; a textview and an edittext. The value of

width for edittext set tomatch parent. The parent for both components is the linear

layout(horizontal).Whenbothwidthsaresettomatchparent,bothwillautomatically

dividedtheirsizeintohalfmatchingtheirparent.

Componenttreeallowforeasydraganddropcomponenttolayout

Layoutasshowsondevice

Propertiesofwidthandheight

Page 100: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

88

Another tool that useful in designing application interface is the preview button

availableinthelayoutdesigner.Selectthedesiredscreensizeandalsoresolutiontosee

how the layout would look like in specific screen aspect ratio and resolution. Try to

avoidhardcodedvaluetocomponentwidthandheightsinceitwillshowsdifferentlyon

differentscreensizes.

Otherthanscreensizesmenu,screenorientationmenualsoimportantiftheapplication

interface isexpected towork in landscapeorientation.Everycomponentaddedto the

layoutportraitmodeinshouldalsoviewinlandscapemodetoseetheconsistencyofthe

position.

Although there are many different techniques that can be used to accommodate

differencescreensizesuchastheuseofsp,dp,pxvaluesaccordingtocomponenttype,

it is important to always test application interface on different screen sizes using the

abovetoolsandadjustaccordingly.

7.2.2 Scroll View 

Scrollviewisanothergoodlayouttouseinsmallerscreensize.Itallowforcomponent

“outofreach”tobescrollable.Anylayoutdesignforbiggerscreencanbeaccesseasily.

Howeverscrollviewcanonlyholdonecomponentandifanyapplicationwouldconsider

runningonsmallerscreensizesuchasinlessthan4inchshouldadoptthisview.

Tousethisview,changethemainlayouttoscrollview.Theeasiestwayistoaccessthe

xmllayoutfileandrenametheconstraintlayouttoscrollview.

Page 101: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

89

Sincescrollviewcanonlyacceptonechildas itsmember,addanother layout thatwill

become themainparent layout toother layoutor components. Any other component

willusethisastheirparentreference.

7.2.3 Layout weightsum and layoutweight 

Sometimes aligning multiple components might get quite tricky. Another easy way

ensuring that each component get good alignment is by using weightsum and

layoutweight. Any componentswithin a parent layout can be set using this property.

ConsidertheabovelayoutwhereLinearLayout(horizontal)containtwocomponents;a

textviewandanedittext.Bothcomponentsisachildcomponent.Thelinearlayoutcanbe

setitsweightsumtoacertaintotalweightthatwillsharedamongchildren’s.

Page 102: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

90

Parentlayoutanditschildcomponents.

TheparentlinearlayoutcontainsweightSumoptionthatsetto1oranyothervaluethat

sumupallthechildspercentage.Childcomponentsuchastextviewwithlayoutweight

setto0.8andfortheedittextsetto0.2.Thetextviewwilloffsetby0.8from1whichwill

onlyoccupy20%oftheparentlayoutandfortheedittextwillholdtherestof80%.Such

optionwill allow components to have consistent layoutwidth throughout any screen

sizes.

Page 103: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

91

TOPIC 8 

8.0 MULTIMEDIA 

Media component allow application to use audio/graphic output thus changing the

applicationlookandfeel.Italsoprovidepositivefeedbacktouserwhenperformcertain

functionwithsound.Thistopicwillonlydiscussbasicusageofmultimediacomponent

suchasimageviewandaudioinapplication.

Page 104: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

92

8.1 Image View 

Imageviewisalayoutcomponentthatenablegraphictobeaddedonlayout.Imageview

canbeusedasinformationorgraphicaloutputforcertainoperation.

Instruction 

a) Createanewproject

b) Getordownloadan image.Makesure thenameof the image isall small letter

andwithoutanywhitespaceorspecialcharacter.

c) Dragtheimagefileandputitintores/drawable‐hdpifolder

d) DragtheimageViewcomponentfromImages&Mediapallettothelayout

e) Selectthenameoftheimagefilefromresourcechooser

f) Bydefault,imageViewwillshowthedefaultimageselected

Page 105: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

93

g) Downloadanotherimageandputthisimageintothesamefolder.

h) Addabuttontothelayoutandinsertthefollowingmethodtomainclass.

i) Referthemethodtobuttononclickxml

j) Runtheprojectandpressthebutton.

Page 106: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

94

Code Description 

Thisprojectbasicallychangesthedefaultimagetothesecondimagewhenthebuttonis

press.AsimplemethodtocalltheimageViewobject(line18)andthensettheimageto

newimagefromdrawablefolder(line19).Theimagesmustbeinthedrawablefolderso

resourceRcanaccesstheDrawablefolderandfinallyimagefilenames.

Assignment 

Addmore images to the drawable folder and allow for the button tomove from one

imagetothenext.Addalsoanotherbuttonso the imagecan traverseback to the first

image.

MoreAssignment:Figureouthowtousethefollowingmethodtoenablescreenslide

features.Theideaisthatwhenuserslidethescreentotheleft,previousimagewillshow

up and alsowith sliding to the rightwhere the next imagewill be displayed. Use the

followingcodeasguidetoimplementthisfeature.

Page 107: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

95

8.2 Media Player 

Audio file can provide audible and conformation feedback for user when accessing

certain task or layout component. It allow user to realize that certain action such as

press a button has been performed. Android MediaPlayer class enable audio file in

certainformattobeplayed.Itusesnovisiblelayoutobjecttoaccessandruntheaudio

file.

Instruction 

a) Createanewproject.

b) Getordownloadanaudiofilein.mp3or.wavformat.Makesurethenameofthe

fileisallsmallletterandwithoutanywhitespaceorspecialcharacter.

c) Create anew folder in resource folder andname the folder as “raw” and then

addanaudiofiletothisfolder.

Page 108: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

96

d) Addthefollowingmethodinmainclass.

e) CallthemethodfromonClickbuttonXML

f) Runtheprojectandpressthebutton.

Code Description 

Thisprojectisasimpleaudioplayerthatplaysashortsoundwhenthebuttonispress.A

toast message is shown to indicate that the audio is playing. This project uses

MediaPlayerclassobject(mp)andreferthisobjecttoasoundfilelocatedinrawfolder

(line18).Theobjectthenexecuteamethod(start)tostartplayingtheaudio(line19).

This is quite useful to implement button click operation or any other conformation

operationprovidinguserwithpositivefeedback.

Page 109: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

97

Assignment  

Further extend the project to include 3 buttons and 2 TextView to create a complete

musicplayercompletewithmusicnames,musicduration,andbuttonsthatenableplay,

pauseandstopoperations.

MakeonClickreferenceoneachbuttontotheirrespectedmethod.

Page 110: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

98

TOPIC 9 

9.0 INTERFACE DESIGN SUGGESTION 

Addingasmalltweaktotheinterfacewillbringsomevaluetoapplicationusability,look

andfeel,andmoreappealingtouser.Hereafewsimpletipstomakeapplicationmore

“attractive”withonlysmallchanges.

Page 111: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

99

10.1 ScrollView Layout 

Eclipsewill use relative layout as its default layoutwhen new Android application is

created.Howeverrelativelayoutisquitedifficulttohandleduetoitsrelativepositioning

tolayoutandcomponentsavailableinthelayout.Componentsometimemoveonitsown

or suddenly change its location when new component is added or moved. Relative

layoutmanagementalsosufferfromsmallscreensizeproblemiftheinterfacecontains

toomanylayoutcomponents.ThisproblemcanbemitigatedbyusingScrollViewlayout

as itsparent layout.This layoutbasicallyenablesapplication tobescrollableonsmall

screendeviceorinhorizontalscreenorientation.Onasmallerscreensize,Ifapplication

contain a lot of interface component, the application will automatically become

scrollabletoallowaccessto“outofscreen”component.

Soitisadvisableifnecessaryforanewprojectwithquiteanumberofcomponentonthe

layouttochangethedefaultlayouttoScrollViewasparentlayoutandthesecondlayout

asmain layout since ScrollViewonly allowone component as its child. So scroll view

layoutmustbeaccompaniedwithanothermainlayoutsuchaslinearlayoutorrelative

layoutandallothercomponentsmustresideinthismainlayout.

Page 112: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

100

9.2 Changing Component Background Colour 

A simple way of making Android interface to look different is by changing its

background colour of a component. Colour tag is a Hex codes ‐ a six‐digit code

representingtheamountofred,green,andbluethatmakesupthecolour.Anycolourtag

canbeusedforallcomponentandmakingtheapplicationmorevibrantwithcolours.

From the layout, select any component its background properties and add with the

selected colour tag. Colour tag can be obtained from website such as

www.w3schools.com/tags/ref_colorpicker.asp.

Most of the background colour for Android layout component such as text view, text

field,button,etccanbeset.Howeveritisrecommendednottousemorethan3colours

Page 113: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

101

foranygiveninterface.Thecolourmustalsoconsistentthroughouteachlayout.Colour

matching software can be used to get the right colour combination for application

(http://www.colorexplorer.com/colormatch.aspx).

The following layout shows the transformation of layout using simple background

colourchangetoeachcomponent.Theapplicationinterfacetransformintomorevibrant

andrefreshinglook.

9.3 Icon Design 

Iconisalsoanothersmalldesignaspectthatprovidesbigchangesinhowusersaccept

andperceiveapplication. Icon canbedesignat thebeginningofnewproject creation.

Basiciconcreationcanbedoneatconfigurelaunchericonwindowwhennewprojectis

created.Iconselectiondesigncanbechosenfromimage,clipartorbyusingtext.Further

exploremoreonthiswindowandcreateabeautifuliconwithsimpleinterface.

Page 114: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

102

9.4 Custom Button 

Android standardbutton is aplainbuttonwith simple text. Changinghow thedefault

button look isoneway to improveAndroid interface.Custombuttonallow for simple

pressanimationonbuttonpresseffectbychangingbuttonpropertiesusingselector.

Instruction 

a) Createanewproject.

b) Createanewxmlfileindrawable‐hdpifoldercalledstatenormal.xml

c) Access the following website http://angrytools.com/Android/button/ and

designabuttonthatrepresentsstatesnormal.Usealltheoptionsandproperties

availableandoncesatisfiedcopythebutton_shape.xmlcodetostatenormal.xml.

Page 115: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

103

d) Create a second xml file called statepressed.xml 

 

 

 

e) Access the same website and create another button that will represent state press. 

Once satisfied copy the buttonshape.xml to the statepressed.xml file. 

 

f) Create a new xml file called selector.xml in xml folder fill the following XML code in 

this file 

Page 116: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

104

g) Add a button on the layout and set the background of the button to

“@drawable/selector”

h) Runtheprojectandpressthebutton.

Code Description 

A custom button are using selector to change the button properties. A selector tags

(instruction6)allowbuttontochangebetweenpressandnormalcondition.Innormal

condition, buttonwill behave properties as stated in statenormal.xml. Thenwhen the

button is pressed, it change properties to buttonpressed.xml. This method is quite

simpleandcanbeusedwithimagetoreplaceconditionforbothpropertiesfiles.

9.5 Button Click Effect 

Button click sound is also a simple way to provide positive feedback to user. Using

mediaplayerclassandaddasimplesoundsuchasclickoralarmallowusertorealize

thebuttonhasbeenpressed.Makesuretousesmallandshortsound.

9.6 Custom Text Edit 

Android provide standard text edit designwith simple design by default (depend on

systemandOScustom).Usingthecustombuttonselectorconcept, thesamethingcan

alsoapplytotextedit.

Page 117: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

105

Tocreateacustomtexteditusethefollowinginstruction.

Instruction 

a) Createanewproject

b) Addastandardtexteditonlayout.

c) Createanewxmlfileindrawable‐hdpifolderandnameitcustomedittext.xml

d) AddthefollowingXMLcodetothenewlycreatedxmlfile.

<?xml version="1.0" encoding="utf‐8"?> <selector xmlns:Android="http://schemas.Android.com/apk/res/Android"> <item Android:state_pressed="true" Android:state_focused="true">     <shape>         <solid Android:color="#FF8000"/>         <stroke             Android:width="2.3dp"             Android:color="#FF8000" />          <corners             Android:radius="15dp" />     </shape> </item> <item Android:state_pressed="true" Android:state_focused="false">     <shape>         <solid Android:color="#FF8000"/>         <stroke             Android:width="2.3dp"             Android:color="#FF8000" />               <corners             Android:radius="15dp" />            </shape> </item> <item Android:state_pressed="false" Android:state_focused="true">     <shape>         <solid Android:color="#FFFFFF"/>         <stroke             Android:width="2.3dp"             Android:color="#FF8000" />           <corners             Android:radius="15dp" />                               </shape> </item> <item Android:state_pressed="false" Android:state_focused="false">     <shape>         <gradient              Android:startColor="#F2F2F2"             Android:centerColor="#FFFFFF"             Android:endColor="#FFFFFF"             Android:angle="270"         />         <stroke             Android:width="0.7dp"                             Android:color="#BDBDBD" />          <corners             Android:radius="15dp" />                 </shape> </item> 

Page 118: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

106

<item Android:state_enabled="true">     <shape>         <padding                  Android:left="4dp"                 Android:top="4dp"                 Android:right="4dp"                 Android:bottom="4dp"             />     </shape> </item> </selector> 

e) AddAndroid:backgroundtoEditTextentryinlayout.

<EditText         Android:id="@+id/editText1"         Android:layout_width="wrap_content"         Android:layout_height="wrap_content"         Android:layout_alignParentTop="true"         Android:layout_centerHorizontal="true"         Android:layout_marginTop="46dp"         Android:ems="10"          Android:background="@drawable/custemedittext"> 

f) Runtheproject

Description 

Customtexteditallowtheapplicationtochangeitspropertiesduringexecution.Using

selector, each user operation state such as press and normal, change the text edit

behaviour.Changingoptionsvalueintheselectorfilesuchascolour,width,radius,etc.

allowfurtheralterationtotextviewappearance.

9.6 Border 

Thisxmlfilecreateabordertoanycomponent

Makeabackgroundreferencetolayoutorcomponentsuchaschildlayout.

Page 119: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

107

Page 120: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

108

TOPIC 10 

10.0 UNDERSTANDING MENU 

In this topic, a fewother regularly used components such asmenu, popupmenu and

actionbarwillbediscussed.

Page 121: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

109

10.1 Android Menu 

Androidprovidemenusystemtofurtherextendoperationandoptionsforapplication.

Menu system is automatically included in the programming when application first

created by introducing two overrides methods in the main class. Both methods are

onCreateOptionsMenu and onOptionsItemSelected. Menu creation and operation are

providedbybothmethods.

Tocreatemenuanditsoperationusethefollowinginstruction.

Instruction 

a) Createanewproject.

b) Toaddmenuaccessmain.xmlfilefrom/res/menu/main.xml

c) Openthefileandaddnewitemtonewmenuelement.

d) Changetitleforthenewlycreateditemandsavethefile.

Page 122: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

110

e) Fromthispointiftheapplicationisrun,newmenuhasbeencreated.

f) Toaddoperationwhenuserclickontheselectedmenu,addthefollowingcodeif

“block statement” (marked by red rectangle box) to onOptionsItemSelected

method.

g) Runtheproject.

Description 

Menucreationandoperationisquitesimpletoimplement.Toaddanewmenusimply

addnewitemtothemain.xmlfileinmenufolder.Toregisteroperationforthemenu,a

simple“ifstatement”blockforeachmenucanbeaddedforeachmenuitemid(line33to

line 37). Any instructionwithin this “if statement” blockwill be executed depend on

menuidselected.Returntrue(line36)isneededforeachcompletedifblockstatement.

10.2 Popup Menu 

Apopupmenuisanothertypeofmenuthat“popup”fromselectedlayoutcomponenti.e.

bypressingabutton.Aseriesofmenuwillappearunderthebuttonviewandusercan

Page 123: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

111

selectitemfromit.Themenucreationissimilarwithstandardmenuacceptfortheclass

thathandlepopupmenu.

Instruction 

a) Createanewproject.

b) Addabuttontothelayout.

c) CreateanewXMLfileunder/res/menu/folderandgive itanamepopup.xml.

(Hint:dragandreleasemain.xmltomenufolderandrenametodifferentname)

d) Create3newmenuitemsasfollow.

e) Implement onMenuItemClickListener on main class level and add

unimplementedmethod.

f) Addthefollowingmethodtothemainclassandreferittobuttononclick.

g) Modify the onMenuItemClick method to add 3 “if statement” block represent

eachmenu.

Page 124: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

112

h) Runtheprojectandpressthebutton.

Description 

Popup menu uses menuitemclick listener to implement its item click operation. The

implementationofthelistenerinthisexampleisbythemainclass.Anoverridemethod

(onMenuItemClick) is implementedtotheclass.ThenashowPopupmethod isusedto

createpopupobjectandsetittothelistener.Finallyaseriesof“ifstatement”blockthat

representtheoperationforeachmenuisaddedtotheoverridemethod.

10.3 Action Bar 

Theactionbar is a layout featureat the topof the application interface thatprovides

identities to the user screen, provides user actions and some navigation modes. The

actionbarcanofferuserwithsomeadditionaloptionsandfeaturessuchas:

Page 125: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

113

A dedicated space for giving app identity and indicating the user's current

locationintheapp.

Makesimportantactionsprominentandaccessibleinapredictableway(suchas

Search).

Supports consistent navigation and view switching within apps (with tabs or

drop‐downlists).

Enabling Action Bar Button 

Actionbarbuttonissimplyamenuwithforcedondisplay.Thebuttonispartofmenu

and behaves like a menu with all components in standard menu options. Use the

AndroidMenuprojectandmodifyoneofthemenuitemswiththefollowingattributes:

Thetitlesetforthemenuwillappearifthebuttonispressforlongertime.Iconselected

inthisexampleisthedefaulticonprovided(greenAndroid).Thiscanbechangedusing

different icon imagebyaddingmore icontodrawable‐hdpi folder.Makesure the icon

filenameonlycontainlowercase,nowhitespace,nonumber,andnospecialcharacter.

Tochangeiconsettheiconattributetotheiconfilename.FinallysettheShowasaction

toalways.Thiswillforcethebuttontoalwaysappearontheactionbar.

Operationonactionbarbutton iswhenthebutton ispresswill remain thesamewith

standardmenuoperationusing the onOptionsItemSelectedmethod. Thebuttonmenu

canalsoimplementonClickviewmethod.Trytoreruntheproject.

Page 126: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

114

Page 127: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

115

TOPIC 11 

11.0 INTENT 

Intentisanabstractdescriptionofanoperationtobeperformed.Itcanbeusedtocalla

newlayout,startotherAndroidapplication,startservices,andmanymore.Inthistopic,

a few intents operations will be introduced such as run new layout, phone and sms

application.

Page 128: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

116

11.1 Layout Intent 

Layoutintentisintenttoopenanotherlayoutfromthemainlayout.Itcanbefromclick

of a button, menu or any other layout component or method that calls the Intent.

Application that requiresmore than one layout screenwill be required to implement

intenttoloadthesecondlayout.

Instruction 

a) Createanewproject.

b) Addabutton to themain layoutand text view. Inside text viewset text insert

“FirstLayout”.

c) Createasecondlayoutandnameitactivity_second.xml.Insidetextviewsettext

insert“SecondLayout”.

d) CreateasecondclassnameitSecondActivity.Java

e) UpdateSecondActivityonCreatemethodsetContentViewtoactivity_secondxml

layout(line13).

f) RegisterSecondActivity.Javatomanifest.xml

AccessApplicationtabandpress“Add”buttonandselectActivity

Page 129: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

117

SelectbrowseNameinAttributesforActivity.FinallyselectSecondActivityclass

andsavethemanifestfile.

g) Add the followingmethod to yourMainActivity.Java.Java and call thismethod

fromactivity_main.xmlbuttononClick.

h) Runtheprojectandpressthebutton

Page 130: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

118

Description  

This example allow user to run a second layout screen using a class activity. Each

activity class for example MainActivity.Java responsible to load the selected layout

(activity_main.xml) describe in onCreate method. If new layout added, another class

activityneededto load thesecond layout.Thisclasshoweverneedtoberegistered in

themanifestfile(instruction6).Tocallthesecondlayout,anIntentclassobjectisuseto

startthesecondclass(instruction7).

11.2 Caller 

CallerisabuildinapplicationprovidedbyAndroidoperatingsystem.Itusestoperform

callerapplicationforusertocallsomeone.

Instruction 

1. Createanewproject

2. Addabuttononthelayout.

3. Addthefollowingviewmethodthemainclass.

4. CallthismethodfrombuttononClickproperties.

5. Addthefollowingpermissioninprojectmanifestfile.

SelectUsesPermission

Page 131: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

119

SelectpermissionCALL_PHONEandsavethemanifestfile.

6. Runtheprojectandpressthebutton.

11.2 SMS 

SMS is an application use to send short message over GSM network. It is a build in

applicationprovidedbyAndroidandcanbeaccessfromIntent.

Instruction 

a) Createanewproject.

b) Createthefollowinglayout

Page 132: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

120

c) Addthefollowingmethodtothemainclass

d) AddthismethodtothebuttonsendonClickproperties.

e) AddSEND_SMSusespermissioninprojectmanifest.

f) Runtheproject,fillphonenumberandtextmessageandpresssendbutton.

Page 133: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

121

TOPIC 12 

12.0 ASYNCTASK AND WEBSERVICES 

Asynctaskclassenableandroidapplicationtorunittaskasbackgroundthread.Thiswill

enable certain task such as downloading data from internet or number crunching

operation to run.Webserviceon theotherhandallowsAndroidapplication toaccess

andretrievedatafromawebserver.

Page 134: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

122

12.1 Asynctask 

TheAsyncTask class allows to run instructions in thebackgroundand to synchronize

again with the main thread. It also reporting progress of the running tasks and also

allows the interface not to freeze. AsyncTasks should be used for short background

operationswhichneedtoupdatetheuserinterface.Operationsuchasonlinedatabase

accesswherethereisnoguaranteewhenthedatacanberetrievedisagoodexampleto

useAsynctask.

 Instruction 

a) Createanewproject.

b) Createthefollowinglayout:

c) UpdateMainActivity.Java.Javawiththefollowingcode

Line 22 define runner object that instantiate from AsyncTaskRunner class

definedbelow.Therunnerobject thenrunexecutesmethodwithcycleTimeas

itspassingparameter.

d) Complete theMainActivity.Java.Javawith the followingAsyncTaskRunner class

withintheMainActivity.Java.class.

Page 135: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

123

e) MakeanonClickreferenceofrunMemethodonthebutton.

f) Importalltherelevantclassandruntheproject.

Theinterfaceshouldupdateforcyclewhenrunbuttonispress.

TherearetwomoremethodsavailableinAsynctaskclass:

onPerExecute method can be used to prepare before the object enter

doInBackground method such as setting up progress dialog. onPostExecute

method will execute at the end of all other methods. This is where all the

“cleanup”isbeendone.

Page 136: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

124

12.2 Web Service 

WebserviceallowsAndroidapplication toaccesswebserverservicesandaccessdata

such as XML, database or JSON data. Asyntask class play important role in enabling

accesstowebserver.

Instruction 

a) Createanewproject.

b) Adduses‐permissionInternetinAndroidManifest.xml

c) Designthefollowinginterface

d) UpdateMainActivity.Java.Javawiththefollowinginterface

e) MakeareferenceofconvertmethodtobuttononClick.

f) ContinuewithMyExchangeasynctaskclasswithinMainActivity.Java.class.

Page 137: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

125

g) FinallywithreadFilemethod.

h) Import all required classes (ctrl+shift+o) and run the project.Write exchange

rateintheedittextfortheratetoconverttoUSD.

Page 138: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

126

Page 139: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

127

TOPIC 13 

13.0 ANDROID DATA STORAGE 

Androidprovideseveralmechanismtostoredataeither locallyoronline. Simpledata

storage uses shared preference to store simple data such as user preference. This is

useful for keeping user application setting such as profile, score etc. SQLite is a local

database where it allows full database capability and it is store within application

storagedirectory.Foronlinedatabasewhereapplicationaccessdatastore inaserver,

Androidutilizewebservicestocommunicatewith

Page 140: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

128

13.1 Shared Preference 

Sharedpreference is away to store and retrievepreferred data inAndroidwhen the

application is closed and restarted. This feature handles by Preferences and

SharedPreferencesclasses.

Instruction 

a) Createanewproject

b) Createnewxmlfileforpreference.Selectnew/AndroidXMLFile.Selectresource

typeaspreferenceandelementasPreferenceScreen.

c) AddEditTextandCheckBoxprefenceinthexmlelement.Provideuniqueidfor

each.

d) CreateaclassforthepreferencecalledPrefClass

Page 141: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

129

e) Inthemainactivity,addabutton,checkboxandTextView.

f) Addthefollowingcodetothemainactivity

Page 142: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

130

g) RegisterthePrefClassactivityinthemanifest

h) Runtheproject.

Page 143: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

131

13.2 Offline Database Application 

Offline database application is a functional database application operation that allow

usertoaccessandstoredatainadatabaseformat.Usercanperformstandarddatabase

operations such as add, delete, update, and search. All the data is stored locally and

query is done using SQL statement. Android uses SQLite as its local database system.

UnderstandinghowSQLstatementworkisanadvantagesincealltheoperationisbased

onSQLquery.

Instruction 

Thisproject isasimplestudententrysystemthatstoredatasuchasnameandmatric

number.Therearefourdatabaseoperations;add,delete,update,andsearch.

CreateanewAndroidprojectanddesigntheapplicationlayoutasfollow.Usescrollview

layoutasmainviewlayout.

Thisprojectinterfacecontainsonlytwoinputsfromedittext,fourbuttons,alistviewand

twotextviews.Eachcomponentarearrangewithinitsownrespectedparentlayout.

Create database and table 

Thefirstoperationistocreatedatabaseandtableforcustomer.Fromthelayout,there

are4fieldsthatbelongtothecustomer.

DatabaseName dbstudentTableName student

Page 144: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

132

Fields/Type NAME(VARCHAR)MATRIC(VARCHAR)

a) Tocreateoropendatabasedefinethefollowingobjectinmainclass

b) Thenaddthefollowingmethodinmainclass

c) CallthismethodfromonCreatemethod.

d) RuntheprojectonAVD.Basicallywhatthissectiondoes is tocreateoropena

databasenamedbstudentandcreatetablestudentwith2fields.

Insert data 

Thesecondoperationistoinsertdatafromtheuserinput.

a) Addthefollowingmethodtothemainclass.

Page 145: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

133

b) Callsthemethod(insertdata)fromaddbuttononClickproperties.

c) Runtheprojectandaddadata.

Assignment:Usefieldchecking foreachEditTextandalsoconformationdialogbefore

proceedwithinsertdataoperation.

Show Data 

Anydataaddtodatabasehiddeninthedatabasestructureinafilesystem.Toviewdata

fromdatabasealistviewcanbeusedtoshowallthedatainthedatabase.

a) Addthefollowingmethodtothemainclass.

Page 146: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

134

b) Call this method when in the oncreate method and also in the last line of

insertdatamethod.

c) Runtheprojectagainandinsertanotherdata.

Assingment:Clearedittextcontentonce the insertoperationhasbeencompleted.

Alsomakesurematricnumberisuniquedataandcanonlybeaddedtodatabaseif

thematricisnotexist.

Delete Data 

ThisoperationwillrequireasimpleSQLdeletequery todeleteparticularcustomer id

fromthetextfield.

a) Addthefollowingmethodtothemainclass.

Page 147: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

135

b) CallthismethodfromthedeletebuttononClickproperties.

c) Run the project. Insert an id to delete in customer id field and press delete

button.

Assignment:Add a field checking formatric number and alsomake sure the

data that user want to delete is available in the database. Add confirmation

dialoguebeforedeleting.

Search 

Searchoperationallowusertosearchdataindatabaseusingcustomeridaskeyword.

a) Addthefollowingmethodtothemainclass.

Page 148: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

136

b) ReferthismethodfromsearchbuttononClickproperties.

c) Runtheprojectandinsertmatricnumberandpresssearchbutton.

Update 

Update operation can be done usingmatric number as key id. User can only update

name.

a) Addthefollowingmethodtothemainclass

b) ReferthismethodfrombuttononClickproperties.

c) Runtheprojectandupdateanameusingselectedmatricnumber.

Page 149: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

137

Assignment:checkfordataavailabilityofmatricnumberandalsoconformation

dialogbeforeproceedwithupdatedataoperation.

CurrentlythereisnoofficialwayofviewingSQLitedatabasecreatedintheapplication.

There are severalways of viewing the database such as using third party application

sqlitebrowser. However on the AVD the database need to be extracted from the

applicationdirectoryandloadintotheapplicationforviewing.Ontherealdevice,user

candownloadanyAndroidsqlitebrowser.Howevertheapplicationcanonlybeusedon

arooteddevice.

13.3 Online Database (MySQL) 

Sqlitedescribeintheprevioustopiccanonlystoredatalocallyinsidedevicedirectory.

However if the database is an online database a different method is required. A few

additionalsoftwareandrequirementisneededtoallowAndroidapplicationtoaccessan

onlinedatabaseservice.

Android

AppPHP

Script

SQL

Server

WEBSERVERRequestHTTP

ReturnformattedData(JSON/XML/TXT)

SQL Query

Returnresult

Page 150: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

138

AnyonlinedatabaseoperationmadebyAndroidapplicationwillbehandledbyserver

sidescript.TheapplicationwillrequestHTTPconnectiontoPHPscriptonawebserver.

PHP script will handle all the SQL queries with the database on the server. The SQL

server then will return the query result and later accepted by the script. The server

script then reformats the data into selected format (JSON/XML/TXT/CVS). The data

thenreceivedbytheandroidapplicationfordisplay.

Inthisexamplethereareafewrequirementstoenablealltheservicesdescribeabove.

ApplicationsuchasXAMPthatenablelocalwebserver,

Instruction 

(1) Web and MySQL server 

a) Download and install XAMP (https://www.apachefriends.org/index.html) and

installinyourcomputer

Or

Use existing web hosting service preinstalled with MySQL and Apache web

services.

b) EnableXAMPApacheandMySQLservices.

c) Testyourwebservicesbyaccessinghttps://localhost/xampp/weblink

d) Create a new folder in the web directory (C:\xampp\htdocs) called staff. The

foldercanbeaccessfromwebbrowserusingthehttp://localhost/staff/url.

Page 151: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

139

Database creation 

e) Access phpMyAdmin through XAMPP interface and then access the database

tab.

f) Create a new database called slumber6_staf (or any other name) and press

createbutton.

g) Insidethisdatabasecreateatablewith6fieldsasfollow:

TableName:stafmember

Field Type Updatedbyuid, int(11) primary key

auto_incrementSystem

name, varchar(100)notnull Userstaffid Varchar(10)notnull Userdepartment text User

Usethefollowingsqlstatementinsqltabtocreatetheabovetable.

Thefollowingtableiscreated

Page 152: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

140

Oncethedatabasesetupcompletedwithtableandfields,thenextphaseistocreatephp

scriptthatwillhandleallthedatabaseconnectionanditsoperations.Thescriptneedto

beplacedinaserveractivedirectorywhereitcanbeaccessthroughhtttpprotocol.

 

(2) PHP Database Connection and Operation 

Androidapplicationneedtouseintermediaryservicetoaccesstoanonlinedatabase.In

thisexampleaPHPscriptisusedasserversidescriptingtocommunicateandprocess

all the required operation coming from Android application. PHP scripts function as

intermediator agent that talk to database server (MySQL) on behalf of Android

application.

This section will discuss on the basic database connection and CRUD (Create, Read,

Update,andDelete)databaseoperationsusingPHP.

a) Createaserveractivedirectorythatcanbeaccessfromabrowser.Thisexample

usesliveserverlocatedathttp://slumberjer.com/stafsystem.

Usershouldbeabletoaccesstotheserverdirectoryusinganywebbrowser.Since

thereisnoserverdocumentavailable,thebrowserwillshowaforbiddenaccess.

b) Createdbconnect.phpfileinstafsystemserverdirectoryandwritethefollowing

script.

Page 153: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

141

Make sure to use the correct username,password,and dbname created in the

previoussection.Totestthedatabaseconnectionsuseawebbrowsertobrowse

and execute the script. In this example the url uses

http://slumberjer.com/stafsystem/dbconnect.php

Makesure itreturnsSuccess. Ifnotcheckall theparametersprovidedsuchas

servername,username,password, anddbname.Once the script returnSuccess

removetheelsestatementfromthescript.

PHP Insert Data into MySQL 

c) Createaanotherfileinsert.php inthestafsystemserverdirectoryandaddthe

followingphpscript

Page 154: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

142

Test the script first using web browser tomake sure the data is being insert

properly. The use of GET array allow data to be inserted using URL

http://slumberjer.com/stafsystem/insert.php?name=Razyn&staffid=1232&dept

=Account.Thescriptshouldreturnsuccessandanewentryshouldbeaddedto

database.

Testtheinsertdataoperationusingwebbrowsergetarrayurl.Thebrowserwill

returnsuccessiftheinsertoperationsuccessful.

Datasuccessfullyinsertedintodatabase.

IMPORTANT‐ Please change from GET to POST once the data insert test

completed.

Page 155: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

143

Android Application: Insert Data 

d) Createanewprojectdesignthelayoutasthefollowing:

e) MakeallthenecessaryobjectreferencesinonCreatemethod.

f) CreateanewJavafilecalledRequestHandler.java.Thisclasswillhandleallhttp

requestsfromAndroid.Importalltherelevantclasses.

Page 156: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

144

public class RequestHandler {

public String sendPostRequest(String requestURL,

HashMap<String, String> postDataParams) {

URL url;

StringBuilder sb = new StringBuilder();

try {

url = new URL(requestURL);

HttpURLConnection conn = (HttpURLConnection)

url.openConnection();

conn.setReadTimeout(10000);

conn.setConnectTimeout(10000);

conn.setRequestMethod("POST");

conn.setDoInput(true);

conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();

BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(os, "UTF-8"));

writer.write(getPostDataString(postDataParams));

writer.flush();

writer.close();

os.close();

int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader br = new BufferedReader(new

InputStreamReader(conn.getInputStream())); sb = new StringBuilder();

String response;

//Reading server response

while ((response = br.readLine()) != null){

sb.append(response);

}

}

} catch (Exception e) {

e.printStackTrace(); }

return sb.toString();

}

public String sendGetRequest(String requestURL){

StringBuilder sb =new StringBuilder();

try {

URL url = new URL(requestURL);

HttpURLConnection con = (HttpURLConnection) url.openConnection(); BufferedReader bufferedReader = new BufferedReader

(new InputStreamReader(con.getInputStream()));

String s;

while((s=bufferedReader.readLine())!=null){

sb.append(s+"\n");

}

}catch(Exception e){

} return sb.toString();

}

Page 157: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

145

public String sendGetRequestParam(String requestURL, String id){

StringBuilder sb =new StringBuilder();

try {

URL url = new URL(requestURL+id);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

BufferedReader bufferedReader = new BufferedReader

(new InputStreamReader(con.getInputStream()));

String s;

while((s=bufferedReader.readLine())!=null){

sb.append(s+"\n");

}

}catch(Exception e){

} return sb.toString();

}

private String getPostDataString(HashMap<String, String> params)

throws UnsupportedEncodingException {

StringBuilder result = new StringBuilder();

boolean first = true;

for (Map.Entry<String, String> entry : params.entrySet()) {

if (first)

first = false;

else

result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));

result.append("=");

result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

}

return result.toString();

}

}

Page 158: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

146

g) AddthefollowingmethodintheMainActivity.java

public void insertData(View v){

final String name= edName.getText().toString();

final String id = edId.getText().toString();

final String dept = spDept.getSelectedItem().toString();

class AddUser extends AsyncTask<Void,Void,String> {

ProgressDialog loading;

@Override

protected void onPreExecute() {

super.onPreExecute();

loading = ProgressDialog.show(MainActivity.this,

"Insert","...",false,false);

}

@Override

protected String doInBackground(Void... params) {

HashMap<String,String> hashMap = new HashMap<>();

hashMap.put("name",name);hashMap.put("staffid",id);

hashMap.put("dept",dept);

RequestHandler rh = new RequestHandler();

String s = rh.sendPostRequest

("http://slumberjer.com/stafsystem/insert.php",hashMap);

return s;

}

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

loading.dismiss();

if (s.equals("success")){

Toast.makeText(MainActivity.this, "Success",

Toast.LENGTH_LONG).show();

}else{

Toast.makeText(MainActivity.this, "Failed",

Toast.LENGTH_LONG).show();

}

}

}

try {

AddUser addU = new AddUser();

addU.execute();

}catch(Exception e){}

}

Page 159: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

147

h) CallthemethodinsertDatafromtheaddbuttononclickxml.

i) AddthefollowingusespermissiontoAndroidManifest.xml

j) Runtheprojectandfillalltherequiredfieldsandpresssave.

Anewentryhasbeeninsertedintodatabase.

Display Data 

Display data from database to application is important so that user know the data

successfully inserted into database. In this example, a custom listview will be use to

displaydatafromdatabase.

a) Createanewphpfile(search.php)inserverdirectoryhandlingthesearchquery.

Page 160: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

148

Try to run the script from a web browser. It should return data in JSON text

format.

ThebrowserreturnsJSONdata.

Page 161: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

149

JSONdatastructureformatted.

b) Addlistviewtothelayout.

Page 162: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

150

c) AddthefollowingmethodtoMainActivity.javaandimportallrelevantclasses.

private void showStafListView(){ //show all user in list view

userlist = new ArrayList<>();

class ShowStaff extends AsyncTask<Void,Void,String> {

ProgressDialog loading;

@Override

protected void onPreExecute() {

super.onPreExecute();

loading = ProgressDialog.show(MainActivity.this,

"Loading","..",false,false);

}

@Override

protected String doInBackground(Void... params) {

HashMap<String,String> hashMap = new HashMap<>();

RequestHandler rh = new RequestHandler();

String s = rh.sendPostRequest("http://slumberjer.com/" +

"stafsystem/search.php",hashMap);

userlist.clear();

if (s != null) {

try {

JSONObject jsonObj = new JSONObject(s);

JSONArray userd = jsonObj.getJSONArray("user");

for (int i = 0; i < userd.length(); i++) {

JSONObject c = userd.getJSONObject(i); String sname = c.getString("name");

String sid = c.getString("staffid");

String sdept = c.getString("dept");

HashMap<String, String> userls = new HashMap<>();

userls.put("name",sname);

userls.put("id",sid);

userls.put("dept",sdept);

userlist.add(userls);

}

} catch (final JSONException e) {}

}

return s;

}

Page 163: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

151

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

loading.dismiss();

ListAdapter adapter = new SimpleAdapter(

MainActivity.this, userlist,

R.layout.listactivity, new String[]

{"name","id","dept"}, new int[]

{R.id.txtname,R.id.txtid,R.id.txtdept});

lvstaf.setAdapter(adapter);

}

}

try {

ShowStaff showdata = new ShowStaff();

showdata.execute(); }catch(Exception e){}

}

d) Addonelayoutfilecalledlistactivity.xmltores/layoutfolder.Designthelayout

asthecomponentlayoutprovided.

e) Updatetheclassdefinitionasfollow:

f) Finallyupdatetheoncreatemethodasfollows

Page 164: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

152

g) Runtheproject.

All thedata fromdatabaseproperlyloadedduringruntimeinside listview.The

methodnamecannowbeused to reload listviewwhenevernewdata inserted

intodatabase.Addthemethodtoanyoperationthatrequiresdatabaseupdate.

Delete Data Operation 

Delete operation perform similarwith insert operation. The only difference is on the

SQLstatementinphpfilethatinstructthedatabasetodeletethedata.

a) Createnewphpfile(delete.php)intheserverdirectorywiththefollowingcode:

Thescriptwilldeletedatabasedonstaffid.Howeverifnostaffidprovideditwill

deleteallthedata.Addmoreprecautiousmeasurementifneededtomakesure

onlydeletedataifitisexist.

Page 165: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

153

b) AddthefollowingclassinMainActivity.java

public void deleteData(View v){

final String id = edId.getText().toString();

class DelUser extends AsyncTask<Void,Void,String> {

ProgressDialog loading;

@Override protected void onPreExecute() {

super.onPreExecute();

loading = ProgressDialog.show(MainActivity.this,

"Deleting","...",false,false);

}

@Override

protected String doInBackground(Void... params) {

HashMap<String,String> hashMap = new HashMap<>();

hashMap.put("staffid",id);

RequestHandler rh = new RequestHandler();

String s = rh.sendPostRequest

("http://slumberjer.com/stafsystem/delete.php",hashMap);

return s;

}

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

loading.dismiss();

if (s.equals("success")){

Toast.makeText(MainActivity.this, "Success",

Toast.LENGTH_LONG).show();

showStafListView();

}else{

Toast.makeText(MainActivity.this, "Failed",

Toast.LENGTH_LONG).show();

}

}

} try {

DelUser delU = new DelUser();

delU.execute();

}catch(Exception e){}

}

This method basically the same with insert method where it execute http

requesttophpscriptontheserver.Thescriptthenreturneithersuccessornot

todeterminetheoperationresult.

Page 166: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

154

c) Callthismethodfrombuttondeleteonclickxml.

d) Runtheproject.Inputanystaffidintheedittextandpressthedeletebutton.The

datawillberemovedandupdatedonthelistview.

Update Data 

Updateoperationalsoperformthesameprocedurethesameasinsertoperation.

a) Create a new php file to handle update data operation. Name the file as

update.php.

b) CreatethefollowingmethodinMainActivity.javaclass

public void updateData(View v){

final String name= edName.getText().toString();

final String id = edId.getText().toString();

final String dept = spDept.getSelectedItem().toString();

class updUser extends AsyncTask<Void,Void,String> {

ProgressDialog loading;

@Override

protected void onPreExecute() {

super.onPreExecute();

loading = ProgressDialog.show(MainActivity.this,

"Updating","...",false,false);

}

Page 167: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

155

@Override

protected String doInBackground(Void... params) {

HashMap<String,String> hashMap = new HashMap<>();

hashMap.put("staffid",id);

hashMap.put("name",name);

hashMap.put("dept",dept);

RequestHandler rh = new RequestHandler();

String s = rh.sendPostRequest

("http://slumberjer.com/stafsystem/update.php",hashMap);

return s;

}

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

loading.dismiss();

if (s.equals("success")){

Toast.makeText(MainActivity.this, "Success",

Toast.LENGTH_LONG).show();

showStafListView();

}else{

Toast.makeText(MainActivity.this, "Failed",

Toast.LENGTH_LONG).show();

}

}

}

try {

updUser updU = new updUser();

updU.execute();

}catch(Exception e){}

}

c) CalledthismethodfrombuttonupdateonClickxml.

d) Run the project to test the update operation. Insert a staff id as key data and

changenameordepartmentfortheselectedstaffidandpressupdate.Verifythe

datahasbeenupdatedfromphpMyAdmininterfaceorfromthelistview.

Search Data 

Searchdataistheoperationofsearchingthedatabasebasedonkeydataandreturnsthe

query to the layout with record or data. Search operation requires some additional

operationsinceitinvolvereturndata.ReturndataisinJSONdatastructureandmustbe

processedtoextracttherequireddata.

a) Create a new php file to handle update data operation. Name the file as

searchsingle.phpandtheninsertthefollowingphpcode.

Page 168: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

156

b) CreatethefollowingclassinMainActivity.Java.class

public void showStafSingleListView(View v){ //show all user in list view

final String id = edId.getText().toString();

userlist = new ArrayList<>();

class ShowStaffSingle extends AsyncTask<Void,Void,String> {

ProgressDialog loading;

@Override

protected void onPreExecute() {

super.onPreExecute();

loading = ProgressDialog.show(MainActivity.this,

"Loading","..",false,false);

}

@Override

protected String doInBackground(Void... params) {

HashMap<String,String> hashMap = new HashMap<>();

hashMap.put("staffid",id);

RequestHandler rh = new RequestHandler();

String s = rh.sendPostRequest("http://slumberjer.com/" +

"stafsystem/searchsingle.php",hashMap);

userlist.clear();

Page 169: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

157

if (s != null) {

try {

JSONObject jsonObj = new JSONObject(s);

JSONArray userd = jsonObj.getJSONArray("user");

for (int i = 0; i < userd.length(); i++) {

JSONObject c = userd.getJSONObject(i);

String sname = c.getString("name");

String sid = c.getString("staffid");

String sdept = c.getString("dept");

HashMap<String, String> userls = new HashMap<>();

userls.put("name",sname);

userls.put("id",sid);

userls.put("dept",sdept);

userlist.add(userls);

}

} catch (final JSONException e) {}

}

return s;

}

c) Addthemethodnametobuttonsearchonclickxml.

d) Run the project to test the search operation. Enter staff id as key and press

buttonsearch.Ifthedataisavailablefromdatabase,therestofthetexteditwill

displaythesearchinformation.

Listview Operation 

Toenableitemonclickoperationonthelistviewaddthefollowingcodeintheoncreate

method.

Page 170: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

158

Whenever user select on item on the listview, the selection texts will appear in the

edittext.

Assignment:ForeachCRUDoperationperform:

‐ EditTextvalidation

‐ Datacollision–ifthedataisalreadyinthedatabase

‐ Conformationdialog

‐ Progressbar

13.4 Real Time Database with Google Firebase 

Real timedatabase is anothergoodoption foronlinedatabasewhere itprovidesnear

real time data access. Application that use real time database can access data on the

server in continuousmanner. Any changes introduced to the data will reflect on the

applicationwithoutdelay.However,notallapplicationwillrequiresuchfeature.

GoogleproviderealtimedatabaseservicethroughitsFirebasesolution.Itisfreetouse

withcertain limitationandupgradablewithpayment ifmoreconnectionsandstorage

needed in the future. This example only covers basic Firebase features such as CRUD

operations.

Firebasedatabasedidn’tusetraditionaldatabasewhereSQLstatementcanbeusedto

manipulatedata.ItreliesonflatfilestoredinJSONdataformat.JSONstoredformatted

datainastructuredefineasfollows:

Page 171: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

159

These example provide basic structure to store student information such as name,

matricandcourse.TherearetwostudentsintheaboveJSONexample.

Instruction 

(1) Create project in Google Firebase console 

LogintotheGoogleConsoleusingthefollowinglinkhttps://console.firebase.google.com

andcreateanewproject.Thisprojectcanhostmultipleapplicationsinit.

Firebase console provide a number of features for development purposes such as

authentication,database,storage,andhosting.

(2) Create new Android Project and Register App 

CreatenewprojectinAndroidStudio.Giveprojectanamesuchas“FirebaseExample”or

any other names that suitable. Once completed get the package name and select Add

application to project using add app button in Firebase console. Then select “Add

Firebase to yourAndroidApp”button.Use thepackagename in theAndroidpackage

nameentry.Leavetherestoftheentryempty.Press“RegisterApp”buttontocontinue.

Page 172: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

160

(3) Login Google account in Android Studio and Register Firebase to app 

OpenAndroidStudioandloginusinggoogleaccount.Theloginoptionisavailableatthe

toprightcorneroftheAndroidStudio.

Once logincompleted, access theFirebaseoption throughmenuTools/Firebase.Open

theRealtimedatabaseoptionfromassistantmenuandpresssaveandretrievelink.

Page 173: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

161

Complete step 1 and 2 of the assistant and accept all the changes needed.Make sure

bothoptionsturntogreen.Closetheassistantoncecompleted.Duringdevelopmentof

Firebaseapplication,itisrequiredthattheInternetisalwaysaccessable.

(4) Setup permission and Interface 

AddInternetusespermissioninManifest.xmltoallowtheapplicationtoaccessInternet.

OncedefinestartwithInterfacedesign for themain layout.Usethe followingguideas

reference.Makesurethelayoutheightsetcorrectlyforeachcomponent.Useconstraint

layoutifpossible.

Page 174: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

162

Create another layout for custom listview. Name the file as customlist.xml. Use the

followingfigureasguideline:

Finally create the third layout called prompt_layout.xml. This layout will be used as

custompopuplayoutforsearchfeature.

(5) Programming  

CreateanewclassfilecalledStudent.java.Fillthefilewiththefollowingcode:

@IgnoreExtraProperties public class Student { public String name;

Page 175: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

163

public String matric; public String course; public Student(){ //default constructor } //setter constructor public Student(String matric, String name, String course) { this.matric = matric; this.name = name; this.course = course; } public String getName(){//getter method return name; } public String getMatric(){//getter method return matric; } public String getCourse(){//getter method return course; } }

CreateanotherJavafilecalledStudentList.Javaandwritethefollowingcodeinside:

public class StudentList extends ArrayAdapter<Student> { private Activity context; List<Student> students; public StudentList(Activity context, List<Student> students) { super(context, R.layout.customlist, students); this.context = context; this.students = students; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.customlist, null, true); TextView textViewName = (TextView) listViewItem.findViewById(R.id.textName); TextView textViewMatric = (TextView) listViewItem.findViewById(R.id.textMatric); TextView textViewCourse = (TextView) listViewItem.findViewById(R.id.textCourse); Student student = students.get(position); textViewName.setText(student.getName()); textViewMatric.setText(student.getMatric()); textViewCourse.setText(student.getCourse()); return listViewItem; } }

AccesstheMainActivity.javaandwritethefollowingcode:

Objectdefinition:

Page 176: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

164

public class MainActivity extends AppCompatActivity { private EditText ed1,ed2,ed3; private DatabaseReference databaseStudent; List<Student> students; ListView listViewStudent;

OnCreatemethod:

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = (EditText) findViewById(R.id.edName); ed2 = (EditText) findViewById(R.id.edMatric); ed3 = (EditText) findViewById(R.id.edCourse); FirebaseDatabase.getInstance().setPersistenceEnabled(true); listViewStudent = (ListView) findViewById(R.id.listStudent); databaseStudent = FirebaseDatabase.getInstance().getReference("Student"); students = new ArrayList<>(); listViewStudent.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Student student = students.get(position); ed1.setText(student.getName()); ed2.setText(student.getMatric()); ed3.setText(student.getCourse()); } }); listViewStudent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { DeleteUser(position); return false; } }); }

OnStartOverridemethod:

@Override protected void onStart() { super.onStart(); databaseStudent.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { students.clear(); for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { Student student = postSnapshot.getValue(Student.class); students.add(student); } StudentList studentAdapter = new StudentList(MainActivity.this, students); listViewStudent.setAdapter(studentAdapter); } @Override

Page 177: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

165

public void onCancelled(DatabaseError databaseError) { } }); }

Addusermethod:

public void AddUser(View v) { String name = ed1.getText().toString(); String matric = ed2.getText().toString(); String course = ed3.getText().toString(); if ((!TextUtils.isEmpty(name)) && (!TextUtils.isEmpty(matric)) && (!TextUtils.isEmpty(course))) { DatabaseReference dR = FirebaseDatabase.getInstance(). getReference("Student").child(matric); Student student = new Student(matric, name, course); dR.setValue(student); Toast.makeText(this, "ADD USER SUCCESS", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "PLEASE FILL DATA", Toast.LENGTH_SHORT).show(); } }

DeleteStudentMethod:

public void DeleteUser(final int position){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setMessage("Delete?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int ida) { //databaseStudent.removeValue().; Student student = students.get(position); DatabaseReference dR = FirebaseDatabase.getInstance(). getReference("Student").child(student.getMatric()); dR.removeValue(); Toast.makeText(MainActivity.this, "DELETED", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }) .show(); }

Updatestudentmethod

public void updateStudent(View v){ String name = ed1.getText().toString(); String matric = ed2.getText().toString(); String course = ed3.getText().toString(); DatabaseReference dR = FirebaseDatabase.getInstance().getReference

Page 178: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

166

("Student").child(matric); Student student = new Student(matric, name, course); dR.setValue(student); Toast.makeText(getApplicationContext(), "Student Updated", Toast.LENGTH_LONG).show(); }

PromptMatricMethodforSearch:

public void promptMatric(View v){ LayoutInflater li = LayoutInflater.from(this); View promptsView = li.inflate(R.layout.prompt_layout, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder.setView(promptsView); final EditText userInput = (EditText) promptsView .findViewById(R.id.editTextDialogUserInput); alertDialogBuilder .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { searchData(userInput.getText().toString()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); }

Searchmethod:

public void searchData(String matric){ DatabaseReference dR = FirebaseDatabase.getInstance(). getReference("Student"); Query query = dR.orderByChild("matric").equalTo(matric); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot data:dataSnapshot.getChildren()){ Student student = data.getValue(Student.class); ed2.setText(student.getMatric()); ed1.setText(student.getName()); ed3.setText(student.getCourse()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }

Page 179: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

167

Finallywithclearfieldmethod:

public void clearFields(View v){ ed1.setText(""); ed2.setText(""); ed3.setText(""); }

All the viewmethods should be referred to their respective button from onClick xml

option.

(6) Run the project 

Access the Firebase console and open the databasemenu. Any data inserted into the

databasewillbearrangedinthefollowingstructure:

Page 180: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

168

TOPIC 14 

14.0 BROADCAST RECEIVERS, SERVICE, ALARM MANAGER 

This topic will look at three types of special purpose classes that enable specific

operations. Broadcast receiver allows application to wait for predetermined set of

message from system or other application and trigger its operation. Service type

applicationallowsapplicationtorunandbehaveasservicewhereAndroidwillkeepits

operationactive in thebackground.AlarmManagerallowsapplication touseAndroid

alarmmanagertotriggeractionbasedontimesetbyapplication.

Page 181: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

169

14.1 Broadcast Receivers 

Broadcast Receivers allow for Android application to “talk” or “listen” to each other

message.Itallowsapplicationtorespondtobroadcastmessagesfromotherapplications

orwithinthesystemitself.Thesemessagesaresometimecalledeventsor intents.For

example,applicationscan initiatebroadcasts to letotherapplicationsknowthatsome

data has been downloaded to the device and is available for them to use, so that a

broadcastreceiverwhowill interceptthiscommunicationandwill initiateappropriate

action.

Therearetwowaystoenablethisfeature;registerviaManifestordynamicallyregister.

Registering via Manifest 

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and

overriding theonReceive()methodwhereeachmessage is receivedas a Intentobject

parameter. Broadcast receiver class handle all operation for any detected event

registeredinManifest.

Instruction 

a) CreateanewProject

b) AccessManifest.xmlapplicationtab/applicationnodesandaddareceiver.

c) SelectthenewlycreatedreceiverandtotherightclickonName

Page 182: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

170

d) Givethereceiverclassaname

e) Anewclassshouldbeautomaticallycreatedasfollow

f) OpenthefileandaddatoastinonReceivemethod

g) Goback toManifest file and add an Intent Filter and then add “Action” to the

Receiver.

Page 183: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

171

h) Application nodes should look like this. Add tag to the action with

AIRPLANE_MODE.

i) OpenMainActivity.Java.classandupdatethecodewiththefollowing

j) Runtheproject.Turnonandofftheairplanemodeforyourdeviceandasimple

Toastshouldappearwhenactioncompleted.

Register Broadcast Programmatically 

Instruction 

To register broadcast through programming is rather easy. Use the following code in

MainActivity.Java,importallrelevantclassesandruntheproject.

Page 184: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

172

Description 

Enablingbroadcast receiver throughprogramming requireanobject (line17)defined

by class that extendBroadacastReceiver (line 23).An intent filter object defined (line

18)theaction(line19)needed.Therearemoreactionsthatcanbeused:

Line20registerthebroadcastreceiverobjectandactionfilterobject.Anyactiontrigger

bytheselectedactionimplementbythemethoddefinedinline25.

Someotheractionthatcanbetriggercanbefoundinthefollowingtable:

Event Constant Description

Android.intent.action.BATTERY_CHANGED Sticky broadcast containing the charging state, level, and other

Page 185: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

173

information about the battery.

Android.intent.action.BATTERY_LOW Indicates low battery condition on the device.

Android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low.

Android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting.

Android.intent.action.BUG_REPORT Show activity for reporting a bug.

Android.intent.action.CALL Perform a call to someone specified by the data.

Android.intent.action.CALL_BUTTON The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.

Android.intent.action.DATE_CHANGED The date has changed.

Android.intent.action.REBOOT Have the device reboot.

14.2 Android Service 

Androidservice isa “backgroundapplication” that runs in thebackground toperform

long‐runningoperationswithoutneedingtointeractwiththeuserinterfaceanditworks

evenifapplicationisno longerrunorhasbeendestroyed.Forexampleanapplication

thatkeepstrackofauseractivitysuchaswalking,running,cycling,andetc. Aservice

has life cycle callback methods that you can implement to monitor changes in the

service'sstateandyoucanperformworkattheappropriatestage.

Instruction 

a) Createanewproject

b) OpenManifestandaccessApplicationNodes

c) Addservice

Page 186: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

174

d) Selectnewlycreatedserviceandthenclickonname

e) Providenamestotheservice

f) Addanmp3filestoresourcefolder.

g) AddunimplementedmethodtothenewlycreatedMyService.javafile

Page 187: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

175

h) AddthefollowingmethodstoMainActivity.Java

i) CreatetwobuttonsonlayoutandaddonClickreferenceforeachmethodin(7).

j) Runtheprojectandpressstartservicebutton.Atoastandmusicwillplayalong.

Theapplicationcanbeputtobackbypressinghomebutton.Howeverthemusic

willcontinueplayinginthebackgroundindicatingtheservicehastakenoverthe

executionofmusicplaying.

Page 188: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

176

14.3 Alarm Manager 

AndroidAlarmManagerserviceallowsapplicationtoaccessbuildinsystemalarm.Other

thanuseinstandardclockalarmmanager,itcanusetoscheduleapplicationtorunata

specific time in the future.TheAndroidAlarmManagerworksbyholdingaCPUwake

lockthatprovidesguaranteenottosleepthephoneuntilbroadcastishandledeventhe

applicationthatinitiatetheservicenolongerrunning.

Example Application: Music Player as Service 

Theapplicationwillplaymusiconcethetimeexpires.

Instruction 

a) Createanewapplication

b) Createthefollowinginterface

c) CreateanewreceiverinManifest/applicationnodes

d) Openthenewlycreatedclassandupdatewiththefollowingcodes.

Page 189: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

177

e) Addasoundfileinres/rawfolder.

f) OpenMainActivity.Javaclassandaddthefollowingviewmethod

g) MakeonClickreferencefortheviewmethodin(6).

h) Runtheapplication

Page 190: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

178

 

 

 

 

TOPIC 15 

15.0 SENSORS, GOOGLE MAP AND LOCATION MANAGER 

Sensorisoneoftheimportantcomponentsthatmakeasmartdevice“smart”. Sensors

collect information from environment and feed the data to application for further

processing.GoogleMapisoneoftheAPIprovidebyGoogle.TheAPIallowsdeveloperto

integrate the map into their application. Location Manager allows access to location

sensoravailableonthephone.Itallowapplicationtogetlatitudeandlongitudedataof

thedevicelocation.

Page 191: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

179

15.1 Sensor 

Sensorcandetectandcollectinformationfromitssurroundingenvironmentandallow

devicetorespondthroughitsapplication.Forexample,whenuseranswersaphonecall

andthenplacethephonenearhis/herfacetotalk,thephonescreensuddenlyturnsoff.

Thisisbecauseoftheproximitysensorthatdetectthefaceisnearandturnthescreen

off.

There are varieties of sensor available in Android devices such as gyroscope,

accelerometer,proximity, temperature,magnetometerandetc. Each sensorallows for

specific functionthatapplicationneeds to functionor interactwithuser.AndroidSDK

provideSensorandSensorManagerclassestoaccesssensoroperation.

Get All Available Sensors 

The following code example will show all available sensor/s in an Android device.

Create a new project and add the following code in the MainActivity.Java.Java and

importalltherelevantclass.Runtheprojectinarealdeviceonly.Thisapplicationwill

listallavailablesensorsinthedevice.

Access to specific sensor  

Thissectionwilllookathowtoaccesstospecificsensoranditsoperation.

a) Createanewproject

b) ImplementSensorEventListenertotheclassandaddunimplementedmethod.

Page 192: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

180

c) UpdatecodefortheoverridemethodsonSensorChanged

d) UpdatethefollowingcodetotheonCreatemethod

e) Add3TextView’stotheactivity_main.xml.

f) Runtheprojectonrealdevice.

Page 193: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

181

Description 

Theprocessstartedfromline28wheresensormanagerobjectgivenaccesstoAndroid

sensor service. Then in line30, sensorobjects select sensor type that theapplication

needs.Fromline33to35,sensorobjectwillcheckifthesensorisavailableornotinthe

device.Finallyline39registersensorManagerobjecttothelistenerthatimplementby

the class. Line 50 to 55 is the listener method implemented by the class. When the

sensor object register with it, the sensor will always provide value to the listener

methodandexecuteinstructionwithinthismethod.

15.2 Google Map 

GoogleMapisoneofthepopularapplicationsinAndroidthatallowusertosearchand

navigate location by using an interactivemap. It provides a highly detailedmapwith

easytousenavigationandtrafficinformation.Theapplicationisalsofreetouse.

Google also allow for google map to be used as application programming interface

services so application developer can use it in their application. Google map API

provided by Google Play services extension to the Android SDK and is available as a

downloadablepackagefromtheSDKManager.Thedownloadincludestheclientlibrary

andcodesamples.TodevelopusingtheGooglePlayservicesAPIs,GooglePlayservices

must be downloaded in the SDK manager. A series of instructions are needed to

completebeforeGoogleMapAPIcanbeintegratedintoAndroidapplication.

Preparation 

ThisphaseisonlyneededoncebeforeanynewapplicationcanuseGoogleMapAPI.Due

to the recent update to Android SDK with Android Studio, the needed library is no

longeravailableandfurtheractionneededtoenableGooglePlaylibraryinEclipse.

a) OpenAndroidSDKManagerandmakesure“GooglePlayservices”underExtra

folderhasbeeninstalled.Ifnotproceedwithinstallation.

b) Download google play services revision 28 from the following link https://dl‐

ssl.google.com/Android/repository/google_play_services_8298000_r28.zip and

unzipthefile.

Page 194: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

182

c) Import project in the “\\google‐play‐services\libproject\google‐play‐

services_lib” to the workspace. Make sure there is no error in the project

directory.Makesurethislibraryprojectkeptopen.

Google Map Project  

ThispartiswhereforeverynewGoogleMaprelatedprojecthastofollow.

a) Createanewproject.

b) Get SHA1 fingerprint key of the computer from menu Window/Preferences‐

Android/Build.

c) Set project library to google‐play‐services_lib from project

properties/Android/Library

Page 195: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

183

d) Generate google API key using the SHA1 fingerprint. This will need access to

Google developer at https://console.developers.google.com/. This will require

Googleaccountaccess.

e) Open Google Maps Android API link and enable this feature. This is very

important!

f) Accesscredentialmenuandcreatenewcredential

g) SelectAPIKeyandAndroidKey

Page 196: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

184

h) AddpackagewithnameandSHA1fingerprintcertificateid

InsertpackagenameexactlythesamewiththeprojectnamecreatedforGoogle

mapapplicationineclipse.UseSHA‐1fingerprintextractedearlier.

i) CopytheAPIkeyprovided

j) AccessprojectAndroidManifest.xmlandaddtwometadatatoapplicationnodes

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="google map API key here" />

Replacethesecondmeta‐datavaluewiththeonegeneratedfromGoogleAPIkey

k) AddapermissiontotheAndroidManifest.xml

Page 197: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

185

<permissionandroid:name="com.example.googlemapexample.permission.MAPS_RECEIVE"android:protectionLevel="signature"></permission>

l) Add5otheruses‐permission<uses-permissionandroid:name="com.example.googlemapexample.permission.MAPS_RECEIVE"/><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permissionandroid:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

m) AddusesfeaturesintheManifestextra

<uses-feature android:glEsVersion="0x00020000" android:required="true" />

n) Addthefollowingfragmenttoactivit_main.xml

<fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.MapFragment" />

o) Runtheproject

Page 198: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

186

p) CompleteAndroidManifest.xmlforreference<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.googlemapexample" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="18" />

<permission android:name="com.example.googlemapexample.permission.MAPS_RECEIVE" android:protectionLevel="signature"> </permission> <uses-permission android:name="com.example.googlemapexample.permission.MAPS_RECEIVE"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission

android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature android:glEsVersion="0x00020000" android:required="true" />

<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyD9Gb3dYgggLVp599uoBD6QPehNHERkhAA" /> </application></manifest>

15.3 Google Map Object Manipulation 

MapobjectallowforfurthermanipulationandoperationfortheGoogleMap.

Instruction 

Usethepreviousproject.

a) AddthefollowingcodetotheMainActivity.Java.Java

Page 199: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

187

@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myMap = ((MapFragment) getFragmentManager()

.findFragmentById(R.id.map)).getMap();myMap.setMyLocationEnabled(true);myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);myMap.setOnMapClickListener(this);myMap.setOnMapLongClickListener(this);

}

Import all the relevant class and run the project. Line 10 defines GoogleMap

objectmyMap.Line16makesareferencetomapidonlayout.Line18and19are

someexampleofmethodsavailableusingthemyMapobjectsthatallowcurrent

locationbuttonandsetmaptypetohybrid.

b) Addsomeinteractivemarkertomap.ModifytheMainActivity.Java.Javawiththe

followingcode.Importallrelevantclassneeded.

Page 200: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

188

1. package com.example.googlemapexample;2. 3. import com.google.android.gms.maps.CameraUpdateFactory;4. import com.google.android.gms.maps.GoogleMap;5. import com.google.android.gms.maps.GoogleMap.OnMapClickListener;6. import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;7. import com.google.android.gms.maps.MapFragment;8. import com.google.android.gms.maps.model.BitmapDescriptorFactory;9. import com.google.android.gms.maps.model.CameraPosition;10. import com.google.android.gms.maps.model.LatLng;11. import com.google.android.gms.maps.model.MarkerOptions;12. 13. import android.app.Activity;14. import android.os.Bundle;15. 16. public class MainActivity extends Activity implements17. OnMapClickListener, OnMapLongClickListener{18. 19. GoogleMap myMap;20. 21. @Override22. protected void onCreate(Bundle savedInstanceState) {23. super.onCreate(savedInstanceState);24. setContentView(R.layout.activity_main);25. myMap = ((MapFragment) getFragmentManager()26. .findFragmentById(R.id.map)).getMap();27. myMap.setMyLocationEnabled(true);28. myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);29. myMap.setOnMapClickListener(this);30. myMap.setOnMapLongClickListener(this);31. 32. }33. 34. @Override35. public void onMapClick(LatLng loc) {36. // TODO Auto-generated method stub37. MarkerOptions marker = new MarkerOptions().position38. (new LatLng(loc.latitude, 39. loc.longitude)).title(loc.toString());40. marker.icon(BitmapDescriptorFactory.defaultMarker41. (BitmapDescriptorFactory.HUE_ROSE));42. myMap.addMarker(marker);43. 44. }45. 46. @Override47. public void onMapLongClick(LatLng arg0) {48. // TODO Auto-generated method stub49. CameraPosition cameraPosition = new50. CameraPosition.Builder()51. .target(arg0).zoom(12).build();52. myMap.animateCamera(CameraUpdateFactory.53. newCameraPosition(cameraPosition));54. }55. }

Page 201: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

189

This will allow user to click on themap and add a marker with latitude and

longitudeinformation.

15.3 Location Manager 

Location manager allow Android application to access GPS sensor available in an

Androiddevice.ThesensorprovidesGPSrelatedinformationofthecurrentlocationof

thedevicesuchaslatitudeandlongitude.Suchdataisusefulincertainapplicationthat

usesusercurrentlocationinformationtofunction.

Instruction 

a) Createnewapplication

b) AccessAndroidManifest.xmlandaddusespermissionofthefollowing:

<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>

c) AddtwoTextViewtoactivity_main.xml

d) AddthefollowingcodetoMainActivity.java

e) CompleteAndroidManifest.xmlforreference.

Page 202: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

190

f) CompleteMainActivity.javaforreference.

1. public class MainActivity extends Activity implementsLocationListener {

2. 3. LocationManager myLocationManager;4. TextView myLatitude, myLongitude;5. 6. @Override7. protected void onCreate(Bundle savedInstanceState) {8. super.onCreate(savedInstanceState);9. setContentView(R.layout.activity_main);10. myLatitude = (TextView) findViewById11. (R.id.TextView1);12. myLongitude = (TextView) findViewById13. (R.id.TextView2);14. myLocationManager = (LocationManager) 15. getSystemService16. (Context.LOCATION_SERVICE);17. myLocationManager.requestLocationUpdates18. (LocationManager.GPS_PROVIDER, 0, 0, 19. this);20. }21. 22. @Override23. public void onLocationChanged(Location arg0) {24. // TODO Auto-generated method stub25. myLatitude.setText(String.valueOf26. (arg0.getLatitude()));27. myLongitude.setText(String.valueOf28. (arg0.getLongitude()));29. }30. 31. @Override32. public void onProviderDisabled(String arg0) {33. // TODO Auto-generated method stub34. }35. 36. @Override37. public void onProviderEnabled(String arg0) {38. // TODO Auto-generated method stub39. }40. 41. @Override42. public void onStatusChanged(String arg0, int arg1, 43. Bundle arg2) {44. // TODO Auto-generated method stub45. }46. }

The class will implements LocationListener and add four additional override

methods. One method that the application will use is sionLocationChanged

method where GPS location change will be called and updated through the

listener.Line22myLocationManagerobjectaccessthelocationservicewherein

Page 203: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

191

line24theobjectthenregisterwithLocationListenerwithpresetGPSasdefault

provider.

g) Run the project. Enable GPS location feature of the phone and wait until the

latitudeand longitude informationappear in theTextView.Thismight require

going outside since GPS provider needs an open sky to receive GPS satellite

information.

15.4 Geocoder and Reverse Geocoder 

Geocodingistheprocessofconvertingaddressnamesorotherdescriptionofalocation

into(latitude,longitude)coordinateandalsofindingseverallocationsaddressthatuse

the same names/descriptions. Reverse geocoding is the process of transforming a

(latitude, longitude) coordinate into a (partial) address. The amount of detail in a

reversegeocodedlocationdescriptionmayvary,forexampleonemightcontainthefull

streetaddressoftheclosestbuilding,whileanothermightcontainonlyacitynameand

postalcode.

Geocoder Example 

Convertingplacesdescriptionornamesintolatitude/longitude/listofaddresses.

a) Createanewproject.

b) Designthefollowinglayout

Page 204: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

192

c) UpdatethefollowingcodeinMainActivity.java

public class MainActivity extends Activity {

EditText ed1, ed2, ed3;ListView lv1;TextView tv1;

private ArrayAdapter<String> adapter;

Geocoder geocoder;final static int maxResults = 10;List<Address> locationList;List<String> locationNameList;

@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ed1 = (EditText) findViewById(R.id.editText1);ed2 = (EditText) findViewById(R.id.editText2);ed3 = (EditText) findViewById(R.id.editText3);tv1 = (TextView) findViewById(R.id.textView1);lv1 = (ListView) findViewById(R.id.listView1);geocoder = new Geocoder(this, Locale.ENGLISH);locationNameList = new ArrayList<String>();adapter = new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item, locationNameList);

lv1.setAdapter(adapter);}

public void searchLoc(View v) {String locName = ed1.getText().toString();try {

locationList = geocoder.getFromLocationName(locName, maxResults);if (locationList == null) {

Toast.makeText(getApplicationContext(), "Not found", Toast.LENGTH_LONG).show();

} else {locationNameList.clear();for (Address i : locationList) {

if (i.getFeatureName() == null)locationNameList.add("unknown");

elselocationNameList.add(i.getAddressLine(0) + "," + i.getAddressLine(1) + "," + i.getAddressLine(2) + ", " + i.getLocality());

}adapter.notifyDataSetChanged();

}} catch (Exception e) {}

}}

Page 205: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

193

d) Importalltherelevantclasses(Ctrl+Shift+o)andruntheproject.

Reverse GeoCoder Example 

a) Updatetheaboveprojectactivity_main.xmllayoutwiththefollowinginterface.

Page 206: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

194

b) AddanotherviewmethodinMainActivity.java

public void revGeo(View v) {double lat = Double.parseDouble(ed2.getText().toString());double lon = Double.parseDouble(ed3.getText().toString());try { List<Address> addresses = geocoder.getFromLocation(lat, lon, 1); if (addresses != null) {

Address add = addresses.get(0);StringBuilder strAdd = new StringBuilder("Address:\n");for (int i = 0; i < add.getMaxAddressLineIndex(); i++) { strAdd.append(add.getAddressLine(i)).append("\n");} tv1.setText(strAdd.toString());} else { tv1.setText("No Address returned!");

} } catch (IOException e) {

tv1.setText("Cannot get Address!"); }

}

c) Make all the necessary reference to all objects in the methods. Also onClick

referencetothesecondbuttonwiththeabovemethod.

d) Importalltherelevantclassesandruntheproject.

Page 207: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

195

TOPIC 16 

16.0 PUBLISHING ANDROID APPLICATION 

AndroidGooglePlayStoreisanapplicationthatallowsAndroidapplicationdeveloperto

uploadandselltheirapplicationworldwide.Howeverthereareafewprocessneededto

complybeforedevelopercanhavetheirapplicationinGooglePlay.

Page 208: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

196

16.1 Registration 

a) Step 1: Go to https://developer.android.com/index.html and open “developer

console”

b) LoginusingGoogleaccount

c) AccepttheDeveloperAgreementandcontinuewithpayment.ThereisUS25one‐

timepaymentfeetobecomeAndroiddeveloper.

Readandticktheagreementacceptance.

Page 209: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

197

d) Continuewiththepayment

e) Finally complete yourdeveloperdetails. Itmay take24hours to complete the

accountandpaymentverifications.

f) Oncecompletedaccessthedeveloperconsole.Theconsolecontainsallthetools

neededtomanageAndroidapplicationinGooglePlayStore.

Page 210: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

198

16.2 Application Upload Preparation 

a) PressAddnew application button to addnew application. Add title andpress

PrepareStoreListing.

b) Upload APK file to Google Play. APK file is an installer file for Android

application.

SomepreparationneededbeforeAPKfilecanbeuse.

i. Makesureprojectpackagedidn’t contain “example”aspartof thepackage

nameforexample:

ii. Makesureprojectisfreefromerror.

iii. Select project from project explorer and right click to “Export Android

Application”

Page 211: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

199

iv. Proceedwithprojectchecks.Thisprocesswillcheck theprojectagainstall

applicationreleaserequirement.

v. Proceedwithcreatenewkeystoreselection.Thisprocesswillgenerateakey

filethatdeveloperneedstokeepduringthelifetimeoftheapplications.Any

newupdatetotheapplicationwillrequirethiskey.

Page 212: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

200

vi. Proceedwithkeycreation.Setvalidationfor25yearsifnecessarybasedon

developerrequiment.

vii. Finallysetdestinationtostorekeyandcertificate

viii. TheAPKfileisreadytobeuploaded.CheckonthedestinationAPKfile.Make

suretokeepthekeyfileforupdatingtonewversionoftheproject.

Page 213: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

201

c) Preparestore listingbyprovidingshortdescriptiontotheapplicationandalso

fulldescription.

d) Some graphics asset needed such as project icon (512x512) and application

screenshot forvariousscreensize.Applicationpromographic(1024x500)also

required.

e) Proceed to content rating questionnaire. This will basically provide rating for

applicationandcomplywithregulationsforcertainnationsandratingstandard.

Page 214: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

202

f) Thensetpricingfortheapplication.IftheapplicationsettoFree,itcanbeonly

doneonceandcannotrevertasPaidapplication.

Page 215: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

203

g) FinallytheapplicationcanbepublishedinGooglePlay

Itmaytake24hoursforapplicationtobepublishedinGooglePlay.

Page 216: Surviving Android Programming with Android Studio · qwertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghjkl zxcvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuiop

SurvivingAndroidProgrammingwithAndroidStudio

204

The Author 

MrAhmadHanisisoneoftheacademicstaff inUniversitiUtaraMalaysia(UUM)since

2009.Hehasvastexperiencedinteachingundergraduateandpostgraduatestudentin

information technology related subject in the university. He’s also involved in many

researchprojectsincomputerscienceandinformationtechnologyfields.He’salsoone

oftheactivetrainerforInternetworkResearchLab(IRL)andalsoCoPed,atrainingunit

under School of Computing, UUM. Since 2013 until now he has been appointed as

assistantmanagerfortheunitandhadbeenactivelyinvolvedinhandlingtrainingatthe

universitylevelandalsotooutsideorganizationsuchasMARA,JMTI,Terengganustate,

Kedahstate,KISMEC,CommunityColleagueandetc.He’smaintrainingsubjectsarein

the area of computer networking (IPv6, networking), operating system (Linux and

Windows), computer programming (Java, VB.net, C++), and mobile application

development (Android, IOS, and Windows Mobile). The author also involved in

commercial android application such as Smartbus Ticketing Solution and Malaysian

MobileJobSearch.HealsoactiveasGooglePlayApplicationdeveloperandownseveral

applicationsinthestore.Hecanbecontactedviaemail;[email protected].