Android Tutorial For Beginners - Part 1 - Ray Wenderlich
Android Tutorial For Beginners - Part 1 - Ray Wenderlich
AndroidTutorialforBeginners:Part1RayWenderlich
Updatenote:Thistutorialwasupdatedforthelatestversionof
AndroidStudiobyDarrylBayliss.OriginaltutorialbyMattLuedke.
ButwhendoestheAndroidversioncomeout?
ThefirstblogcommentafteranyiOSappgetsannounced.
ClearlytheresademandforAndroidappdevelopment,andits
turningtheplatformwiththelovablegreenmascotintomoreand
moreofastrongfirstchoiceratherthanjustasecondaryoptionto
iOS.
Withoveronebilliondevicesactivated,Androidisanexcitingspace
tomakeappstohelpyoucommunicate,organize,educate,entertain
oranythingelseyourepassionateabout.
Ifthatsnotenough,hereareafewmorereasonstolearnAndroid:
Youllbepluggedintotheopensourceplatformwith(atthe
timeofpress)thelargestmarketshareofsmartdevices
worldwide.
Androidspoliciesondeviceprovisioningandappsubmission
aremoreopenthanApples,meaningthatonceyoucomplete
yourfirstappasyoulldointhistutorialyouandyour
friendscanenjoyitonyourdevicesrightaway!
IfyouhaveexperiencedevelopingforiOS,youcanbecome
wellversedinthewaysthatthetwoplatformscoincideanddiffer(welldiscussafewinthistutorial)andwhatyou
likeabouteach.Thenyoullhavemoretoolsatyourdisposalforyournextmobileproject.
ItsnotjusttheiPhoneanymore.Therearesomanysmartphones,tablets,glasses,andwatchesoutthere,coming
fromsomanymanufacturers,andtheyrealltryingtojumpintothegame.Youdonthavetobeanysortofmarket
analysttoknowthatthereareafewimportantplatformsandAndroidisoneofthem.
Soifyouvebeenintenton,thinkingabout,orsimplyplayingwiththeideaoflearningAndroidMakeYourFirstAndroid
Appisthetutorialseriesforyou!
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
1/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Therearentanyprerequisitestostart.YoulllearnhowtosetupallthetoolsyouneedtobecomeanAndroiddeveloper
intraining.ThenyoullputtogetheryourownfullfledgedAndroidappfromscratch!Thisappwill,whencompleted,help
yougetdetailsaboutabookyoureinterestedinusingonlinesearchsources.
BytheendofPartThreeofthisseries,yourappwillincludeusefulfeatureslike:
Savingappdatalocallyonthephone.
Loadingandinteractingwithadynamiclistofdata.
Accessinganonlinedatasource.
Sharinglinksthroughsocialnetworks.
Android,andseveralpopularframeworksforit,makeallofthesefeaturesreallysimpletoimplement.Whynotstart
learningthiseasyandpowerfulplatformforyourself,today?
Getting Started
HowdoesAndroiddevelopmentgodown?First,thezoomedoutbasics:
YoullwriteyourprogrammingwhatyouwantyourapptodoinJavafilesanddesignyourlayoutshowyou
wantyourapptolookinXMLfiles.
Onceyourappisready,youlluseabuildtooltocompilealltheprojectfilesandpackagethemtogetherintoa
.apkfilethatyoucanrunonAndroiddevicesand/orsubmittoGooglePlay.
AllofthefilesyouusedtoputyourapptogetheraremanagedbyanIntegratedDevelopmentEnvironment(IDE).
TheIDEistheprogramyouwillopentoedityourcodefilesandtomanageyourprojects.
ThestandardIDEforAndroidusedtobeEclipse,butthisisnowbeingreplacedbyGooglesownAndroidStudio.
Ifyouzoomin(metaphorically),youllfindmoreindepthprocessesgoingonbehindthescenesduringalloftheabove
steps.Forexample,advanceduserswillwanttoinvestigatetheroleoftheDalvikVirtualMachineanditsnew
replacement,ART.
Butfornow,letsmoveon.Hereswhatyouregoingtoaccomplishinthispartofthetutorial:
1. DownloadandinstallAndroidStudio.
2. Setuptestingondevicesandemulators.
3. CreateasimpleHelloWorld!Androidappthatprintstoyourdevicesscreen.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
2/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
4. Makesmalleditstotheappsoitcancongratulateyoubyname.
Inthesecondpartofthistutorial,youllmakeanappthatrecordsamessageyoutype,addsittoalist,savesitinmemory
andsharesitwithfriends.Alongtheway,youlllearnhowtoaddandconfigurevariousUIelementssuchas
ImageViews,Buttons,ListViews,andEditTextcontrols.
Finally,thethirdpartwillcoverhowtomakeanapptosearchanonlinedatabaseofbooks,displayandsharethecover
imagesofthesearchresults,andnavigatebetweenthedifferentscreensofyournewapp!
Note:Justasmuchasyouretraininginprogrammingsyntaxandframeworks,itsimportanttotrainyourselfto
haveasuccessfulprogrammingmindsetonethatwontacceptfileXnotfoundasafinalanswer.90%of
thismindsetissimplytrainingyourselftokeeptryingtillyoufindasolution.
Withallofthisinmind,letsquicklycheckthatyouhavetheJavaDevelopmentKit(JDK)installed.Youmightalready,
evenifyoudontknowforsure.
Tocheck,youllusetheTerminal.IfyoureunfamiliarwiththeTerminal,youmaywanttoreadagoodintroductory
tutorialaboutworkingwiththeTerminal.
Inanutshell,yourTerminalislikelookingunderyourcarshood.Itshowyoureallygettoknowthemachinefaceto
face,withoutanycomplexgraphicalinterfaceinthemiddle.YoucanfindtheTerminalappquiteeasilyonaMacusing
Spotlight.SearchforterminalandclickthetophittorunTerminal.
OnceyouhavetheTerminalopen,typeinjavaversion.Youshouldseesomeoutputthatmentionsaversion
number,likebelow.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
3/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
IfyoudonthavetheJDKinstalled,yourTerminalwilltellyoucommandnotfound.Ifthatsthecase,youshould
downloadtheJDKfromOracle.
Whenready,headovertotheAndroidStudiopageandclickthebiggreenbuttontodownloadthecorrectversionfor
yourOperatingSystem.
Googleisconstantlyupdatingthispage,sotheversionyouseemaybenewerthanthescreenshotabove.Onceyou
haveclickedthebuttonyoullbeaskedtoagreetotheTermsandConditions:
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
4/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Afterreadingthesecarefully(asyoualwaysdo)accepttheTermsandConditionsandclickthebluebuttonunderneath
titledDownloadAndroidStudio.Yourdownloadwillfinallybegin.Itmaytakeafewminutesbutoncefinishedyoucan
installAndroidStudiosimilartoanyotherprogram.
ThedownloadpagewillhelpfullyredirecttoawebpagethatcontainsinstallationinstructionsforOSX,Windowsand
LinuxOperatingSystems.Ifforsomereasontheinstructionsdontappearthenyoucanalsoviewthemhere.
NowthatyouveinstalledStudio,letsfireitup!LaunchAndroidStudio.
OnceAndroidStudiohasfinishedloading,youllbegreetedwiththeSetupWizardthefirsttimeStudioloads.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
5/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
ClickNexttomovetothenextscreen.Thisscreenwillaskwhattypeofsetupyouwouldlike.MakesureStandardis
checkedandclickNextagaintomovetothenextscreentoacceptsomelicensesforcomponentsthatwillbeinstalled
onyourcomputer.
AccepttheseandclickNextonelasttimetobegindownloadingtheextracomponentsyouwillneed.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
6/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
AfterafewminutesyouwillhaveeverythingyouneedtobeginbuildingfantasticAndroidAppsandwillmovetothe
welcomescreen.
EventhoughyoujustdownloadedAndroidStudio,youmightnotactuallyhavethelatestversion.Rightaway,youneed
tochecktoseeifanyupdatesareavailableandifnecessary,followanyinstructionstogetthelatestversion.Youcan
checkwhetheranyupdatesareavailablebyclickingcheckforupdatesatthebottomofthewelcomescreen.
Ifanupdateisavailableyouwillhaveawindowlikethisappear:
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
7/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Whenyouseethisscreen.AlwayschooseUpdateandRestart.Insomecases,youmayneedtodownloadthefull
installerinthatcaseyouwillseeaDownloadbuttonthatwilltakeyoutoinstructionsforinstalling.
Great!Asallprogrammersinthemoviessaywhentheyaresuccessfullygreetedwithanewinterface:Werein!
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
8/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Themenuwillslideacrossandpresentanewmenuwithvariousoptions.TheoptionyouwantistheSDKManager.
ThisisthegotoplaceifyouneedtodownloadaspecificversionofAndroidtodeveloportestyourappon.Italso
containsotherusefulthingssuchasAPIdocumentation,versionspecificcodesamplesandevenpreviewsofsoftware
kitsthatinteractwithAndroidsuchasAndroidWearandGoogleGlass.
FornowletsfocusondownloadingaversionoftheAndroidSDK.ClicktheSDKManageroption,anewwindowwill
presentitselftoyouwithcheckboxes,foldersandstatusesacrossthepage.
Letsmakesomesenseofthis.Eachfolderisadirectoryoftools,softwareanddocumentation.Themajorityofdirectories
arespecifictoanSDKversionofAndroidbuttherearesomethatcatertomultipleversions.Thefirstfolderforexample,
entitledTools,isafolderthatcontainscomponentsthataredesignedtoassistinthedevelopmentofAndroidandwork
acrossmultipleSDKs.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
9/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
TheAndroid5.0(API21)directoryontheotherhandholdseverythingspecifictothatversionoftheAndroidSDK.
IncludingsamplecodefornewfeatureswithintheSDK,APIdocumentationandsystemimagesyoucanusetosimulate
acertainmobilearchitectureusinganAVD.
Ifyoudontunderstandwhatallthismeansthendontworry,justthinkofeachfolderasaplacewhereeachversionof
Androidandtheirtoolslivehappily.FromthelatestpreviewversionrightdowntotheoriginalAndroidBeta(API2).
YoushouldalreadyhavethelatestversionoftheAndroidSDKTools,AndroidSDKPlatformtoolsandAndroidSDK
Buildtoolsdownloadedfromthetoolsdirectory.Ifanupdateforanyofthesetoolsisavailablethenthecheckboxnextto
thetoolwillautomaticallybeticked,alongsideapolitemessageintheStatuscolumnofthewindowtellingyouwhatthe
latestversionis.
FornowletsdownloadthepreviousversionofAndroid,thatbeingAndroid4.4.2(API19).
ClickthetickboxnexttothefoldericonforAndroid4.4.2,thiswillselecteverythingwithinthatdirectoryfordownload.
YoucanalwayscomebacktotheSDKManagertodeleteanythingyoudontuse.
Important:ItsalwayworthopeningtheSDKManagereverytimeyoustartAndroidStudiotoseeifthereisany
updatestoanytoolsorSDKsyouhaveinstalled.Thisensuresyougetaccesstothelatestfeaturesinyour
alongsideanyfixesfornastybugs.
YourSDKManagerwindowshouldlooksomethinglikethis:
ClickInstallxpackages(xbeingtheamountofpackagescheckedfordownload)onthebottomrightoftheSDK
Manager.Anewwindowwillappearwithadropdownlistofthepackagesyouwishtoinstall,simplyclicktherootofthe
dropdownlistandthenclicktheAcceptLicenseradiobuttoninthebottomright.
Youmayneedtodothisformultiplelicensesdependingonwhatpackagesyoudownload.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
10/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Finally,clicktheinstallbuttonattheverybottomrightofthewindowtobeginyourdownload.
ThewindowwilldisappearandtheSDKManagerwillbegintodownloadandinstallyourselecteditems.Gograbadrink
andtakeinwhatyouvejustdonewhilsttheSDKManageristickingaway.Thiswillbecomearegulartaskthatyouneed
togetaccustomedtosoyoucanquicklyacquireandupdatethevariousSDKsyouwanttoworkwith.
OncetheSDKManagerhasfinisheddownloadingandinstallingyouritemsyoucanmoveontocreatingyourfirst
AndroidApp!
11/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
AndroidStudiohasanicelittlestepbysteptooltohelpyoumakeyourproject.ClickStartanewAndroidStudio
ProjectfromtheWelcometoAndroidStudioscreen:
Note:IfyoucurrentlyhaveanAndroidStudioprojectopenandtheWelcomescreenisntshowing,selectFile\New
Projectfromthemenutocreateanewproject.
Studiowillpresentyouwithyourfirstprojectcreationscreen:
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
12/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
EnterOMGAndroidinApplicationnameasshownabove.FeelfreetoputyourownnameintheCompanyDomain
textfield.Asyoutype,youllnoticethePackageNamewillautomaticallychangetocreateareversedomainstylename
basedonyourApplicationnameandCompanyDomain.
ThePackageNameisusedtouniquelyidentifyyourappamongstotherapps,thatwayanyworkanAndroiddevicehas
tobeperformonbehalfoftheappalwaysknowsitssourceandcantgetconfusedbetweentwoapps.iOSdevelopers
willrecognizethisconceptasbeingsimilartotheBundleIdentifier.
YoucansettheProjectlocationtoanylocationonyourharddriveyoudonotneedtofollowthescreenshotforthat
one:]
ClickNextatthebottomofthewindowtoprogresstothenextpartoftheprojectsetup.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
13/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Thenextscreeniswhereyouselectdevicetypesandoperatingsystemstotarget.WantanApptofocusonjustPhone
andTablet?Notaproblem!HowaboutanAppforTVandGoogleGlass?Thatsgreattoo.Fornowthoughyoujustwant
anAppthatworksonanAndroidPhone.Thisoptionisselectedasthedefault,alongsidethedefaultMinimumSDK.
TheMinimumSDKdropdownmenusetstheminimumversionofAndroidneededtorunyourapp.Selectingthisvalue
foryourownprojectsisamatterofbalancingtheSDKcapabilitiesyouwantandthedevicesyouwanttosupport.
Foryourfirstapp,youllusethedefaultAPI16,whichisAndroid4.1(JellyBean).Everyappwillhavedifferent
requirementsandyoumaywanttochoosesomethingelse,dependingonthesituation.
IfyoureallywanttogetintothedetailsofwhatMinimumSDKversionisbestforyourAppthenAndroidStudiocanhelp
youout.AsyouchangetheMinimumSDKinthedropdownmenu,thepercentageinthetextunderneathreflectswhat
percentageofdevicescurrentlyrunthatversionofAndroid.
Ifyouaremoreaboutfeaturesthannumbers,AndroidStudiohasgotyourbacktoo.ClickthehighlightedHelpme
chooseunderneaththedropdownlisttodisplayausefulnewwindow.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
14/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Whatyouarelookingatisabarchart,splitbytheamountsofdevicesrunningaspecificversionofAndroid.Clickonany
partofthebarandthetexttotherightwillchange,tellingyouthemostsignificantfeaturesoftheAndroidVersionthat
partofthebarrepresents.UsefulifyouneedaquickoverviewofwhateachversionofAndroidprovidesforyourApp.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
15/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
TakenoteoftheCumulativeDistributionvaluesontherightofthebar.Thisrepresentsthepercentageofdevices
supportingthatparticularversionofAndroidwhichincludesbackwardscompatibility.Asyoudescenddownthebar,
theversionofAndroidincreasesandyougainmorefeaturesthatyourAppcanmakeuseof.Thedownsidetothisisthe
amountofdevicesthatcanactuallyrunyourAppisreduced.
PickingwhatMinimumSDKyourAppwillrequireisacrucialchoice.Itwillinfluencewhatfeaturesyouhaveavailableto
youinyourprojectwhilealsoinfluencinghowmanyAndroiduserscanrunyourApp.Choosewisely!
FormoreinformationonAPIversionsandtheiruse,checkouttheAndroidDashboards,whichareupdatedeveryfew
days.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
16/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Gettingbacktothenewprojectwindow,clickNextinthebottomrighttopickmoreoptionsforyourproject.
ThisscreenletsyouchooseadefaultActivityforyourapp.ThinkofanActivityasawindowwithinyourAppthat
displayscontenttheusercaninteractwithnotunlikeaViewControlleriniOS.Anactivitycantakeuptheentirescreen
oritcouldbeasimplepopup.
AvailableactivitiesonthistemplaterangefromablankactivitywithanActionBarrightuptoanActivitywithaMapView
embedded.Youwillbemakingalotofactivities,soitsgoodtogetaccustomedwiththem.
SelecttheBlankActivityoptionandclickNext.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
17/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Ifyouhavemadeitthisfarthenwelldone,youareatthefinalscreenbeforeyoudigintosomeactualcoding.Tospeed
thispartupalittlebityouwillusetheprepopulateddefaultvalues,butwhatisactuallydonewiththesevalues?
ActivityName.ThiswillgiveyourActivityanametorefertoincode.Oncetheprojectsetupiscomplete
AndroidStudiowillcreatea.javaclassandusethecontentsofthistextfieldtogivetheclassaname.Thisisthe
nameyouwillusetorefertoyourActivityinsideyourcode.
Note:WhatitsactuallydoingismakingasubclassofActivity.Thosefamiliarwithobjectoriented
programmingwillknowwhatthisis,butfornewcomers,thisbasicallymeansthatyourMainActivityis
goingtobeacustomizedversionofActivitythatactsjustlikethedefaultone,handlingthingslikeits
lifecycleandtheuserinterfacedisplay.
LayoutName.YouregoingtodefineyourActivityinJava,butthelayoutofeverythingitwillshowtotheuseris
definedinaspecialsortofAndroidXML.Youwilllearnhowtoreadandeditthosefilesshortly.
ClickFinish.AndroidStudiotakesthisasitscuetogodoabunchofbehindthescenesoperationsandcreateyour
project.Asitshootsoutsomedescriptionsofwhatitsdoingfromtimetotime,youmaynoticeitsaysomethinglikethe
following:
Youseeyourprojectname,whichisfamiliar.ButthenthereisthisGradleword,andthenamentionofMaveninthe
URL.ThebenefitofhavingamodernIDElikeAndroidStudioisthatithandlesalotforyou.Butasyourejustbeginning
tolearnhowtousethesoftware,itsgoodtoknow,ingeneral,whatitsdoingforyou.
Gradleisanewbuildtoolthatiseasytouse,butitalsocontainsalotofadvancedoptionsifyouinvestigateit
further.IttakesyourJavacodeandXMLlayouts,andthenusesthelatestAndroidbuildtoolstocreatetheapp
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
18/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
packagefile,knownasanAPKfile.Youcancustomizeyourconfigurationstohavedevelopmentorproduction
versionsoftheappthatbehavedifferently,oradddependenciesforthirdpartylibraries.
Mavenisanotherprojectbuildtool,anditcanalsorefertotheMavenCentralrepositoryofjavalibraries.Itis
absurdlyeasytouseGradleandMavenCentralinconcertwithAndroidStudiotoincorporateallsortsof
functionalityfromtheAndroiddevelopmentcommunity.ThosewithaniOSbackgroundwillknowhowcoolthissort
ofthingcanbefromusingtheCocoaPodstool.YoulllearnmoreaboutMaveninPartThreeofthetutorial.
Afterabriefmoment,AndroidStudiowillfinishbuildingyourproject.Theprojectisprettyempty,ofcourse,butitstillhas
everythingitneedsalreadysetupsothatitcanbelaunchedonanAndroiddeviceoremulator.Youwillbedroppedoff
inthisspot:
AndroidStudiowillcontainthreewindows.Totheleftyouhaveyourprojectfolderstructure,themiddlecontainsa
previewofyourlayoutonaNexus5deviceandfinallytherightshowsyourlayouthierarchyaswellasattributesifyou
haveapartofyourlayouthierarchyselected.Beforeyougetintoanyprogramming,letstalkabouthowyouregoingto
getthisapprunning.ItstimetosayHelloworld!
19/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
yourtestingneeds.
Upuntilrecently,yourcomputerwouldhavetoemulateeverythinganAndroiddevicewouldtrytodo.Everythingdown
toitshardwarewhichrunsusinganARMbasedprocessor.Mostcomputersthesedaysmakeuseofx86based
processors,whichmeansyourcomputerwouldbedoingcomputationallyintensetasksthattakeasignificantamountof
timejusttotestyourApp.
Youstillhavetheoptiontodothisifyouwanttocreateanemulatorthatisasclosetoanactualdeviceasyoucan,butbe
awarethattheinitialloadtimeshaveputoffmanyanAndroidDeveloperusingtheemulatoralltogether.
Allofthatbeingsaidletssetupanemulatoranyway,becauseyouregoingtoneedtoknowhow!
ClickAVDManager.ItsthebuttoninthetoolbarthathasanAndroidpoppingitsheadupnexttoadevicewithapurple
display.
Asyouwillsee.AndroidStudiohasalreadycreatedanAVDforyoutouse.Youllseeafewdetailsaboutit,notablywhat
typeofemulatoritis,whatAPIitisusingandwhatCPUinstructionsetituses.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
20/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
LetsrunthroughcreatinganewAVD.ClickCreateVirtualDeviceinthebottomlefttobeginconfiguringanewvirtual
device.
Thefirstdecisionyouneedtomakeiswhattypeofdeviceyouwanttoemulate.TheCategorylisttotheleftshowsallthe
typesofdeviceyoucanemulate.Clickingeachoptionshowsyouwhattypeofdevicesareavailabletoyouinthat
category.FornowyoujustwanttoemulateaphonesizeddevicebutifyouwantedtoemulateanAndroidWearwatchor
anAndroidTVthenyouhaveoptionstodosohere.
SelectNexusSinthelistofdevicesavailabletoyoufromthephonecategoryandclickNext.
YournextdecisionistodecidewhatversionofAndroidyouwantyourvirtualdevicetorun.Youwillalreadyhaveoneor
twoavailabletoyouthankstothesetupwizard,soletsuseoneofthem.
SelectLollipopandmakesuretheoneselectedhasthevaluex86intheABIcolumn.Wewanttheemulatortobe
runningasfastaspossibleonourx86computers.:)
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
21/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
ClickNextoncethisisdonetomovetothefinalscreen.Thelastscreenissimplyaconfirmationofyourpreviouschoices
withtheoptiontoconfiguresomeotherpropertiesofyourdevicesuchasdevicename,startuporientation,andRAM
size.FornowleavethesesetastheirdefaultsandclickFinish
Congratulations!Withrelativeeaseyouvejustcreatedafreshvirtualdevicereadyforusetotestoutyournewapp.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
22/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Now,closetheAVDManagertogobacktoAndroidStudiosmainview.Nowthatyouveconfiguredeverything,theres
butonestepleft
ClicktheRunbutton.Itlookslikeaplayicon.
Anewwindowwillappear,askingyoutochoosethedeviceyouwishtotestyourAppon.Youcurrentlyhavenodevices
running,soletsstarttheAVDyoujustcreated.EnsuretheLaunchEmulatorradiobuttonischeckedandyourAVDis
selectedinthedropdownmenu,thenclickOK.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
23/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Note:IfyougetanerrorthatsaysThisAVDsconfigurationismissingakernelfile!!,checktomakesurethatyou
donthavetheANDROID_SDK_ROOTenvironmentvariablesetfromapreviousinstallationoftheAndroidSDK.
Seethisthreadformoretroubleshootingtips.
Youmayhavetowaitawhileastheemulatorloads,andyoumayevenneedtotryitmorethanoncefortheemulatorto
getitright,butonceitsready,youshouldseesomethinglikethis:
Congratulations!YoumadeyourfirstAndroidapp!
AndroidAppsusedtobesomethingyouonlyinteractedwithontheconsumerside,butnowyoureacreator.Theres
powerandpossibilityinthat.Itsworthtakingamomenttothinkaboutwhereyoumightwanttogowiththisnewfound
ability.
Whenyoureready,youneedtorevisitsomethingIquicklyglossedoverearliertestingondevices.
24/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
aresixmainstrategiesIcanrecommend:
1. Naildownyourtarget
2. Filteryourmanifest
3. CheckAndroidsbestpractices
4. Emulate
5. Pickatleastonerepresentativedevice
6. Fakeotherscreensonyourdevice
Letsgothroughthemonebyone.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
25/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Asthemessagepolitelytellsyou,yournewlyinputvaluesarebeingoverriddenbyaGradleBuildScript.Letsgosee
wherethishappens,doubleclickonthebuild.gradle(Module:App)fileintheGradleScriptsfolderandyouwillbe
presentedwithsomethinglikethis.
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.darrylbayliss.omgandroid"
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguardrules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
26/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Therearequiteafewthingsgoingonhere,butfornowyouwillfocusonjustonepartthedefaultConfigelement.
InsideitscurlybracketsyouwillseesomefamiliarlookingvaluesthatareaffectingyourAppwhenitisbeingcompiled.
ThiswaswhatthemessageinyourManifestwaswarningyouabout.Fortunately,itisntaconcern,butitissomething
worthunderstanding.
WheneveryouclickRuninyourmainprojectwindow,anyvalueswithinthedefaultConfigelementofbuild.gradleare
usedtopopulatesomeadditionalinformationintoyourAndroidManifest.xmlfile.Thereasonforthisistomakeuseof
theflexibilityoftheGradleBuildToolkit.
BeforeAndroidStudio,thingssuchastryingtobuildmultipleversionsofanAppfromthesameprojectwassomethingof
apipedream.AnAppprojectonlyhasonemanifestfiletodeclareitsfeaturesandrulessoifyouwantedtotestdifferent
configurationsofyourApp,itwouldbealongandlaboredprocessbecauseyouwouldhavetomakeyourchanges,
compiletheAppandthenrepeatthisprocessuntilyouwerehappywiththeresults.
ThearrivalofGradlechangesallthat,allowingformultiplebespokeversionsofyourApptobecreatedusingspecific
rulesyoucansetyourself.Projectdependenciescanbelinkedtofromremotecoderepositories,ensuringeverytime
youbuildyourAppyouareusingthelatestversionof3rdpartylibraries.YoucanevensetrulesuptotestyourAPK
usingavarietyofsourcefilesduringthebuildprocess.
GradlemakesuseofGroovysyntax,aJavalikelanguage,soifyouareintentonlearningJavathenyouwilleasilypick
Groovyupaswell.
YoucanlearnmoreaboutGradleanditstreasurechestoffeaturesrighthereontheAndroidDeveloperswebsite.
4. Emulate
WhenyousetupyourEmulatorearlier,yousawhowmanyoptionsyouhavetoworkwithdifferentscreensizes.Ifyou
usedthestockemulatorthenyoualsosawhowslowitcanbe.Asmentionedearlier,therearewaystoimproveitand
alternativeemulatorsalltogetheryoucanmakeuseoftotryyourApponahugevarietyofconfigurations.
Ifthestockemulatorisntforyou,trythemoutandseewhatworksbest.
27/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Othertimes,youhavetodosomeweirdshenanigans.Icantmakethisup!AdirectquotefromAndroid:OnAndroid4.2
andnewer,Developeroptionsishiddenbydefault.Tomakeitavailable,gotoSettings>AboutphoneandtapBuild
numberseventimes.ReturntothepreviousscreentofindDeveloperoptions.
NomatterifyouhadtodoalittledanceorwhistleaperfectCtorevealtheoption,onceUSBdebuggingison,youcan
gobacktotheRun/DebugConfigurationsscreenandsetyourTargetDevicetoUSBDevice.Thiswillserveyouwell
fortherestofthetutorial.
Note:Iftheadbversioncommandresultsinanerrormessage,yourAndroidSDKfolderisprobablynotinyour
PATH.ThenyoudneedtofindtheexactlocationoftheAndroidSDKandchangetothecorrectfolder(asinthefirst
stepsinthescreenshotabove)andprefixanyadbcommandswith./.Alternatively,youcanaddtheadbpathto
yourPATH.
Theadbversioncommandisjustanexampletoshowyouhowtocalladbfromthecommandline.Itcanrunallsorts
ofcommandsandyoucangetalistofavailablecommandsbytypingadbhelp.
Ifnotalreadysetup,youcanoptionallyaddtheAndroidSDKplatformtoolsfoldertoyour$PATHsothatyoucanrunadb
fromanywhereonyoursystem.YoushouldonlydothisifyouarefamiliarwithUNIXandfeelcomfortabledoingso.
Withyourdevicepluggedinandwithitsscreenturnedoff,typethefollowing:
adb shell wm size 640x480
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
28/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Andthentype:
adb shell wm density 160
Thisrepresentsascreensizeof640480pixelswith160pixelsperinchpixeldensity.
Note:InAndroidversionsearlierthan4.3JellyBean,thesecommandsareslightlydifferent,asdocumentedhere.
Whenyouturnthedevicescreenbackon,youshouldseethattheresolutionhaschangedtomatchthenewvaluesyou
entered!
Feelfreetoturnthescreenoff,tryanothersetofdimensionsandturnitbackonagain.
Toreturnyourdevicetoitsnormalsettings,type:
adb shell wm size reset
Andthentype:
adb shell wm density reset
Soyoucouldgetafullsizetablet(likeaNexus10,perhaps)andtheneasilysimulateallsortsofsmallerdevices,without
havingtousetheemulator!Ifyouaretryingthiswithadevicethathasarelativelysmallscreenthenitsnotreallyworth
goingbeyondthedimensionsofyourscreenasitwillbegintodisplayelementsoffscreen.
IhopethatinformationhelpsyounavigatetheGingerbreads,KitKats,JellyBeans,andalltheothervarietiesofAndroid
candy.Now,backtotheappathand
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
29/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Browsearoundforafewminuteswithoutanyexplicitinstructions,expandingandcollapsingfoldersanddoubleclicking
onfilestoseetheircontentsinthemainwindow.Ifyounoticeanytrends,great.Ifitallstilllookscryptic,nottoworry!
30/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Drawablefoldersthatholdimagesjustthedefaultlaunchiconfornow.
ThelayoutfolderwithXMLthatrepresentsthescreendesigns.
ThemenufolderwithXMLoftheitemsthatwillappearontheActionBar.Moreonthatlater.
ThevaluesfolderwithXMLcontainingdimensions,strings,andstyles.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
31/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
Soremember:WhenyoulaunchtheApp,youreessentiallydoingthesamethingassendingalaunchIntenttothe
manifest.Astheboss,themanifesttakesalookattheIntentanddecidesithastheperfectfitforthejob:MyActivity.
TheJavadoestheheavyliftingofopeningthescreen,butforwhattodisplayitgoesandaskstheartist,eventually
leadingtostrings.xml.
ClickRun.WhentheApplaunchesagain,youllseeyourpersonalizedmessage!
Congratulations!Ifyouhaveadevice,youcangoaroundshowingoffyournewapptoyourfriendsortakeascreenshot
fromtheemulatorandsendittothem.
YouveenteredtheworldofAndroid.Youvesetupyourdevelopmentenvironment(noeasytask!),createdyourfirst
app,runitonanEmulatorordevice,andchangedtheAppsothatitspecificallyaddressesyou.Greatjob!
button,whichallowsyoutoeasilydownloador
updateyourAndroidSDKcomponents.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
32/33
10/9/2015
AndroidTutorialforBeginners:Part1RayWenderlich
DarrylBayliss
DarrylBaylissisaSoftwareEngineerfromLiverpool,currentlyfocusingonMobile
Development.
Awayfromprogrammingheisusuallyreading,writingonhisblogorplayingsome
fantasticalvideogameinvolvingmagicanddragons.
FeelfreetosayhelloonTwitterorcheckouthiscodingscribblesonGitHub.
http://www.raywenderlich.com/78574/androidtutorialforbeginnerspart1
33/33