Full Download Android how to program 2nd edition paul deitel PDF DOCX

Page 1


https://ebookgate.com/product/android-how-toprogram-2nd-edition-paul-deitel/ Download more ebook from https://ebookgate.com

More products digital (pdf, epub, mobi) instant download maybe you interests ...

C How to Program 6th Edition Paul Deitel

https://ebookgate.com/product/c-how-to-program-6th-edition-pauldeitel/

C How to Program 9e 9th Edition Paul Deitel

https://ebookgate.com/product/c-how-to-program-9e-9th-editionpaul-deitel/

C How to Program 7th Edition Paul J. Deitel

https://ebookgate.com/product/c-how-to-program-7th-edition-paulj-deitel/

C How to Program Fourth Edition Harvey M. Deitel

https://ebookgate.com/product/c-how-to-program-fourth-editionharvey-m-deitel/

Java How To Program Fourth Edition

Harvey M. Deitel

https://ebookgate.com/product/java-how-to-program-fourth-editionharvey-m-deitel/

Internet World Wide Web How to Program Fourth Edition

P. J. Deitel

https://ebookgate.com/product/internet-world-wide-web-how-toprogram-fourth-edition-p-j-deitel/

JavaScript for Programmers 1st Edition Paul J. Deitel

https://ebookgate.com/product/javascript-for-programmers-1stedition-paul-j-deitel/

Android Tablets For Dummies 2nd Edition Sandra Geisler

https://ebookgate.com/product/android-tablets-for-dummies-2ndedition-sandra-geisler/

Android

Phones

For Dummies 2nd ed Edition Gookin

https://ebookgate.com/product/android-phones-for-dummies-2nd-ededition-gookin/

ONLINE ACCESS

Thank you for purchasing a new copy of Android™ How to Program, Second Edition. Your textbook includes 12 months of prepaid access to the book’s Companion Website. This prepaid subscription provides you with full access to the following student support areas:

• Source code

• Premium web chapters

Use a coin to scratch off the coating and reveal your student access code. Do not use a knife or other sharp object as it may damage the code.

To access the Android How to Program, Second Edition, Companion Website for the first time, you will need to register online using a computer with an Internet connection and a web browser. The process takes just a couple of minutes and only needs to be completed once.

1. Go to http://www.pearsonhighered.com/deitel/

2. Click on Companion Website.

3. Click on the Register button.

4. On the registration page, enter your student access code* found beneath the scratchoff panel. Do not type the dashes. You can use lower- or uppercase.

5. Follow the on-screen instructions. If you need help at any time during the online registration process, simply click the Need Help? icon.

6. Once your personal Login Name and Password are confirmed, you can begin using the Android How to Program Companion Website!

To log in after you have registered:

You only need to register for this Companion Website once. After that, you can log in any time at http://www.pearsonhighered.com/deitel/ by providing your Login Name and Password when prompted.

*Important: The access code can only be used once. This subscription is valid for 12 months upon activation and is not transferable. If this access code has already been revealed, it may no longer be valid. If this is the case, you can purchase a subscription by going to http://www.pearsonhighered.com/deitel/, going to the Android book and following the on-screen instructions.

Deitel®SeriesPage

HowToProgramSeries

AndroidHowtoProgram,2/e C++HowtoProgram,9/E CHowtoProgram,7/E

Java™HowtoProgram,10/E

Java™HowtoProgram,LateObjectsVersion,10/E Internet&WorldWideWebHowtoProgram,5/E VisualC++® 2008HowtoProgram,2/E VisualBasic® 2012HowtoProgram,6/E VisualC#® 2012HowtoProgram,5/E

SimplySeries

SimplyC++:AnApp-DrivenTutorialApproach SimplyJava™ Programming:AnApp-Driven TutorialApproach

SimplyC#:AnApp-DrivenTutorialApproach SimplyVisualBasic® 2010:AnApp-Driven Approach,4/E

CourseSmartWebBooks

www.deitel.com/books/CourseSmart/ C++HowtoProgram,8/Eand9/E

SimplyC++:AnApp-DrivenTutorialApproach Java™HowtoProgram,9/Eand10/E SimplyVisualBasic2010:AnApp-Driven Approach,4/E

(continuedfrompreviouscolumn)

VisualBasic® 2012HowtoProgram,6/E VisualBasic® 2010HowtoProgram,5/E VisualC#® 2012HowtoProgram,5/E VisualC#® 2010HowtoProgram,4/E

Deitel®

DeveloperSeries

AndroidforProgrammers:AnApp-Driven Approach,2/e,Volume1

CforProgrammerswithanIntroductiontoC11 C++11forProgrammers

C#2012forProgrammers

DiveInto® iOS6forProgrammers:AnApp-Driven Approach

Java™forProgrammers,2/e

JavaScriptforProgrammers

LiveLessonsVideoLearningProducts

www.deitel.com/books/LiveLessons/ AndroidAppDevelopmentFundamentals, C++Fundamentals

Java™Fundamentals

C#2012Fundamentals

C#2010Fundamentals

iOS® 6AppDevelopmentFundamentals

JavaScriptFundamentals

VisualBasicFundamentals

ToreceiveupdatesonDeitelpublications,ResourceCenters,trainingcourses,partneroffersandmore, pleasejointheDeitelcommunitieson

•Facebook® facebook.com/DeitelFan

•Twitter® @deitel

•Google+™ google.com/+DeitelFan

•YouTube™ google.com/+DeitelFan

•LinkedIn® linkedin.com/company/deitel-&-associates andregisterforthefree Deitel ® BuzzOnline e-mailnewsletterat: www.deitel.com/newsletter/subscribe.html

Tocommunicatewiththeauthors,sende-mailto: deitel@deitel.com

Forinformationon Dive-Into® Series on-siteseminarsofferedbyDeitel&Associates,Inc.worldwide, writetousat deitel@deitel.com orvisit: www.deitel.com/training/

ForcontinuingupdatesonPearson/Deitelpublicationsvisit: www.deitel.com www.pearsonhighered.com/deitel/

VisittheDeitelResourceCentersthatwillhelpyoumasterprogramminglanguages,softwaredevelopment,AndroidandiOSappdevelopment,andInternet-andweb-relatedtopics: www.deitel.com/ResourceCenters.html

EditorialDirector,ECS: MarciaHorton

ExecutiveEditor: TracyJohnson(Dunkelberger)

DirectorofMarketing: ChristyLesko

MarketingManager: YezAlayan

MarketingAssistant: JonBryant

DirectorofProgramManagement: ErinGregg

ProgramManagement-TeamLead: ScottDisanno

ProgramManager: CaroleSnyder

ProjectManagement-TeamLead: LauraBurgess

ProjectManager: RobertEngelhardt

ProcurementSpecialist: LindaSager

CoverDesign: PaulDeitel, HarveyDeitel, AbbeyDeitel, MartaSamsel

PermissionsSupervisor: MichaelJoyce

PermissionsAdministrator: JenellForschler

Director,ImageAssetServices: AnnieAtherton

Manager,VisualResearch: KarenSanatar

CoverArt: ©OleksiyMark/Shutterstock and ©JustContributor/Fotolia

MediaProjectManager: RenataButera

Creditsandacknowledgmentsborrowedfromothersourcesandreproduced,withpermission,inthistextbookappear onpagevi.

Theauthorsandpublisherofthisbookhaveusedtheirbesteffortsinpreparingthisbook.Theseeffortsincludethe development,research,andtestingofthetheoriesandprogramstodeterminetheireffectiveness.Theauthorsandpublishermakenowarrantyofanykind,expressedorimplied,withregardtotheseprogramsortothedocumentation containedinthisbook.Theauthorsandpublishershallnot beliableinanyeventforincidentalorconsequentialdamagesinconnectionwith,orarisingoutof,thefurnishing,performance,oruseoftheseprograms.

Copyright©2015and2013PearsonEducation,Inc.,publishingasPrenticeHall.Allrightsreserved.Manufactured intheUnitedStatesofAmerica.ThispublicationisprotectedbyCopyright,andpermissionshouldbeobtainedfrom thepublisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmissioninanyformorbyany means,electronic,mechanical,photocopying,recording,or likewise.Toobtainpermission(s)tousematerialfromthis work,pleasesubmitawrittenrequesttoPearsonEducation,Inc.,PermissionsDepartment,OneLakeStreet,Upper SaddleRiver,NewJersey07458,oryoumayfaxyourrequestto201-236-3290.

Manyofthedesignationsbymanufacturersandsellersto distinguishtheirproductsareclaimedastrademarks.Where thosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshavebeen printedininitialcapsorallcaps.

LibraryofCongressCataloging-in-PublicationData

Onfile 10987654321

ISBN-10:0-13-376403-6

ISBN-13:978-0-13-376403-1

InMemoryofAmarG.Bose,MITProfessorand FounderandChairmanoftheBoseCorporation: Itwasaprivilegebeingyourstudent—andmembers ofthenextgenerationofDeitels,whoheardourdad sayhowyourclassesinspiredhimtodohisbestwork. Youtaughtusthatifwegoafterthereallyhardproblems,thengreatthingscanhappen.

HarveyDeitel PaulandAbbeyDeitel

Trademarks

DEITEL,thedouble-thumbs-upbugandDIVE-INTO areregisteredtrademarksofDeitel&Associates,Inc.

JavaisaregisteredtrademarkofOracleand/oritsaffiliates.Othernamesmaybetrademarksoftheir respectiveowners.

Google,Android,GooglePlay,GoogleMaps,GoogleWallet,Nexus,YouTube,AdSenseandAdMob aretrademarksofGoogle,Inc.

Microsoftand/oritsrespectivesuppliersmakenorepresentationsaboutthesuitabilityoftheinformation containedinthedocumentsandrelatedgraphicspublishedaspartoftheservicesforanypurpose.All suchdocumentsandrelatedgraphicsareprovided“asis”withoutwarrantyofanykind.Microsoftand/ oritsrespectivesuppliersherebydisclaimallwarrantiesandconditionswithregardtothisinformation, includingallwarrantiesandconditionsofmerchantability,whetherexpress,impliedorstatutory,fitness foraparticularpurpose,titleandnon-infringement.InnoeventshallMicrosoftand/oritsrespectivesuppliersbeliableforanyspecial,indirectorconsequentialdamagesoranydamageswhatsoeverresulting fromlossofuse,dataorprofits,whetherinanactionofcontract,negligenceorothertortiousaction, arisingoutoforinconnectionwiththeuseorperformanceofinformationavailablefromtheservices.

Thedocumentsandrelatedgraphicscontainedhereincouldincludetechnicalinaccuraciesortypographicalerrors.Changesareperiodicallyaddedtotheinformationherein.Microsoftand/oritsrespectivesuppliersmaymakeimprovementsand/orchangesintheproduct(s)and/ortheprogram(s)describedherein atanytime.Partialscreenshotsmaybeviewedin fullwithinthesoftwareversionspecified.

Microsoft® andWindows® areregisteredtrademarksoftheMicrosoftCorporationintheU.S.A.and othercountries.ScreenshotsandiconsreprintedwithpermissionfromtheMicrosoftCorporation.This bookisnotsponsoredorendorsedbyoraffiliatedwiththeMicrosoftCorporation.

Throughoutthisbook,trademarksareused.Rather thanputatrademarksymbolineveryoccurrenceof atrademarkedname,westatethat weareusingthenamesinaneditorialfashiononlyandtothebenefit ofthetrademarkowner,withnointentionofinfringementofthetrademark.

1 IntroductiontoAndroid1

1.1Introduction2

1.2Android—TheWorld’sLeadingMobileOperatingSystem3

1.3AndroidFeatures3

1.4AndroidOperatingSystem7

1.4.1Android2.2(Froyo)7

1.4.2Android2.3(Gingerbread)8

1.4.3Android3.0through3.2(Honeycomb)8

1.4.4Android4.0through4.0.4(IceCreamSandwich)8

1.4.5Android4.1–4.3(JellyBean)9

1.4.6Android4.4(KitKat)10

1.5DownloadingAppsfromGooglePlay11

1.6Packages12

1.7AndroidSoftwareDevelopmentKit(SDK)13

1.8Object-OrientedProgramming:AQuickRefresher16

1.8.1TheAutomobileasanObject17

1.8.2MethodsandClasses17

1.8.3Instantiation17

1.8.4Reuse17

1.8.5MessagesandMethodCalls17

1.8.6AttributesandInstanceVariables18

1.8.7Encapsulation18

1.8.8Inheritance18

1.8.9Object-OrientedAnalysisandDesign(OOAD)18

1.9Test-Drivingthe Doodlz AppinanAndroidVirtualDevice(AVD)19

1.9.1Runningthe Doodlz AppintheNexus4SmartphoneAVD19

1.9.2Runningthe Doodlz AppinaTabletAVD28

1.9.3Runningthe Doodlz ApponanAndroidDevice30

1.10BuildingGreatAndroidApps30

1.11AndroidDevelopmentResources32

1.12Wrap-Up35

2 Welcome App38

Dive-Into®theAndroidDeveloperTools:IntroducingVisualGUIDesign, Layouts,AccessibilityandInternationalization

2.1Introduction39

2.2TechnologiesOverview40

2.2.1AndroidDeveloperToolsIDE40

2.2.2 TextViewsand ImageViews40

2.2.3AppResources40

2.2.4Accessibility40

2.2.5Internationalization40

2.3CreatinganApp41

2.3.1LaunchingtheAndroidDeveloperToolsIDE41

2.3.2CreatingaNewProject41

2.3.3 NewAndroidApplication Dialog42

2.3.4 ConfigureProject Step43

2.3.5 ConfigureLauncherIcon Step43

2.3.6 CreateActivity Step45

2.3.7 BlankActivity Step46

2.4AndroidDeveloperToolsWindow47

2.4.1 PackageExplorer Window48

2.4.2EditorWindows48

2.4.3 Outline Window48

2.4.4AppResourceFiles48

2.4.5 GraphicalLayout Editor49

2.4.6TheDefaultGUI49

2.5BuildingtheApp’sGUIwiththe GraphicalLayout Editor51

2.5.1AddingImagestotheProject51

2.5.2Changingthe Id Propertyofthe RelativeLayout andthe TextView 52

2.5.3Configuringthe TextView 53

2.5.4Adding ImageViewstoDisplaytheImages57

2.6Runningthe Welcome App59

2.7MakingYourAppAccessible60

2.8InternationalizingYourApp62

2.9Wrap-Up66

3 TipCalculator App69

Introducing GridLayout, LinearLayout, EditText, SeekBar,EventHandling, NumberFormat andDefiningAppFunctionalitywithJava

3.1Introduction70

3.2Test-Drivingthe TipCalculator App71

3.3TechnologiesOverview72

3.3.1Class Activity 72

3.3.2 Activity LifecycleMethods72

3.3.3ArrangingViewswith LinearLayout and GridLayout 73

3.3.4CreatingandCustomizingtheGUIwiththe GraphicalLayout Editorandthe Outline and Properties Windows73

3.3.5FormattingNumbersasLocale-SpecificCurrencyand PercentageStrings74

3.3.6ImplementingInterface TextWatcher forHandling EditText TextChanges74

3.3.7ImplementingInterface OnSeekBarChangeListener for Handling SeekBar ThumbPositionChanges74

3.3.8 AndroidManifest.xml75

3.4BuildingtheApp’sGUI75

3.4.1 GridLayout Introduction75

3.4.2Creatingthe TipCalculator Project77

3.4.3Changingtoa GridLayout 77

3.4.4Addingthe TextViews, EditText, SeekBar and LinearLayouts78

3.4.5CustomizingtheViewstoCompletetheDesign80

3.5AddingFunctionalitytotheApp84

3.6 AndroidManifest.xml 92

3.7Wrap-Up93

4 Twitter® Searches App97

SharedPreferences,Collections, ImageButton, ListView, ListActivity, ArrayAdapter,Implicit Intentsand AlertDialogs

4.1Introduction98

4.2Test-DrivingtheApp99

4.2.1ImportingtheAppandRunningIt99

4.2.2AddingaFavoriteSearch100

4.2.3ViewingTwitterSearchResults101

4.2.4EditingaSearch102

4.2.5SharingaSearch104

4.2.6DeletingaSearch104

4.2.7ScrollingThroughSavedSearches105

4.3TechnologiesOverview105

4.3.1 ListView 105

4.3.2 ListActivity 106

4.3.3Customizinga ListActivity’sLayout106

4.3.4 ImageButton 106

4.3.5 SharedPreferences 106

4.3.6 IntentsforLaunchingOtherActivities107

4.3.7 AlertDialog 107

4.3.8 AndroidManifest.xml 108

4.4BuildingtheApp’sGUI108

4.4.1CreatingtheProject108

4.4.2 activity_main.xml Overview109

4.4.3Addingthe GridLayout andComponents110

4.4.4 GraphicalLayout EditorToolbar115

4.4.5 ListView Item’sLayout: list_item.xml 116

4.5Buildingthe MainActivity Class117

4.5.1 package and import Statements117

4.5.2Extending ListActivity 119

4.5.3FieldsofClass MainActivity 119

4.5.4Overriding Activity Method onCreate 120

4.5.5AnonymousInnerClassThatImplementsthe saveButton’s OnClickListener toSaveaNeworUpdatedSearch122

4.5.6 addTaggedSearch Method124

4.5.7AnonymousInnerClassThatImplementsthe ListView’s OnItemClickListener toDisplaySearchResults125

4.5.8AnonymousInnerClassThatImplementsthe ListView’s OnItemLongClickListener toShare,EditorDeleteaSearch127

4.5.9 shareSearch Method129

4.5.10 deleteSearch Method130

4.6 AndroidManifest.xml 132

4.7Wrap-Up132

5 FlagQuiz App136

Fragments, Menus,Preferences, AssetManager,TweenedAnimations, Handler, Toasts,Explicit Intents,LayoutsforMultipleDeviceOrientations

5.1Introduction137

5.2Test-Drivingthe FlagQuiz App139

5.2.1ImportingtheAppandRunningIt139

5.2.2ConfiguringtheQuiz139

5.2.3TakingtheQuiz141

5.3TechnologiesOverview143

5.3.1Menus143

5.3.2Fragments143

5.3.3FragmentLifecycleMethods144

5.3.4ManagingFragments144

5.3.5Preferences144

5.3.6 assets Folder144

5.3.7ResourceFolders145

5.3.8SupportingDifferentScreenSizesandResolutions145

5.3.9DeterminingtheScreenSize146

5.3.10 ToastsforDisplayingMessages146

5.3.11Usinga Handler toExecutea Runnable intheFuture146

5.3.12ApplyinganAnimationtoa View 146

5.3.13LoggingExceptionMessages147

5.3.14UsinganExplicit Intent toLaunchAnother Activity inthe SameApp147

5.3.15JavaDataStructures147

5.4BuildingtheGUIandResourceFiles147

5.4.1CreatingtheProject147

5.4.2 strings.xml andFormatted String Resources148

5.4.3 arrays.xml 149

5.4.4 colors.xml 150

5.4.5 dimens.xml 150

5.4.6 activity_settings.xml Layout151

5.4.7 activity_main.xml LayoutforPhoneandTablet PortraitOrientation151

5.4.8 fragment_quiz.xml Layout151

5.4.9 activity_main.xml LayoutforTabletLandscapeOrientation154

5.4.10 preferences.xml forSpecifyingtheApp’sSettings155

5.4.11CreatingtheFlagShakeAnimation156

5.5 MainActivity Class158

5.5.1 package Statement, import StatementsandFields158

5.5.2Overridden Activity Method onCreate 159

5.5.3Overridden Activity Method onStart 161

5.5.4Overridden Activity Method onCreateOptionsMenu 161

5.5.5Overridden Activity Method onOptionsItemSelected 162

5.5.6AnonymousInnerClassThatImplements OnSharedPreferenceChangeListener 163

5.6 QuizFragment Class164

5.6.1 package Statementand import Statements164

5.6.2Fields165

5.6.3Overridden Fragment Method onCreateView 166

5.6.4Method updateGuessRows 168

5.6.5Method updateRegions 169

5.6.6Method resetQuiz 169

5.6.7Method loadNextFlag 171

5.6.8Method getCountryName 173

5.6.9AnonymousInnerClassThatImplements OnClickListener 173

5.6.10Method disableButtons 176

5.7 SettingsFragment Class176

5.8 SettingsActivity Class177

5.9 AndroidManifest.xml 177

5.10Wrap-Up178

6 CannonGame App182

ListeningforTouches,ManualFrame-By-FrameAnimation,Graphics,Sound, Threading, SurfaceView and SurfaceHolder

6.1Introduction183

6.2Test-Drivingthe CannonGame App185 6.3TechnologiesOverview185

6.3.1AttachingaCustom View toaLayout185

6.3.2UsingtheResourceFolder raw 185

6.3.3 Activity and Fragment LifecycleMethods185

6.3.4Overriding View Method onTouchEvent 186

6.3.5AddingSoundwith SoundPool and AudioManager 186

6.3.6Frame-by-FrameAnimationwith Threads, SurfaceView and SurfaceHolder 186

6.3.7SimpleCollisionDetection187

6.3.8DrawingGraphicsUsing Paint and Canvas 187

6.4BuildingtheApp’sGUI andResourceFiles187

6.4.1CreatingtheProject187

6.4.2 strings.xml 188

6.4.3 fragment_game.xml 188

6.4.4 activity_main.xml 189

6.4.5AddingtheSoundstotheApp189

6.5Class Line MaintainsaLine’sEndpoints189

6.6 MainActivity Subclassof Activity 190

6.7 CannonGameFragment Subclassof Fragment 190

6.8 CannonView Subclassof View 192

6.8.1 package and import Statements192

6.8.2InstanceVariablesandConstants193

6.8.3Constructor194

6.8.4Overriding View Method onSizeChanged 196

6.8.5Method newGame

6.8.6Method updatePositions

6.8.7Method fireCannonball 201

6.8.8Method alignCannon 202

6.8.9Method drawGameElements 203

6.8.10Method showGameOverDialog 205

6.8.11Methods stopGame and releaseResources 206

6.8.12Implementingthe SurfaceHolder.Callback Methods207

6.8.13OverridingViewMethod onTouchEvent 208

6.8.14 CannonThread:Usinga Thread toCreateaGameLoop209

6.9Wrap-Up210

7 Doodlz App215

Two-DimensionalGraphics, Canvas, Bitmap,Accelerometer, SensorManager, MultitouchEvents, MediaStore,Printing,ImmersiveMode

7.1Introduction216

7.2TechnologiesOverview218

7.2.1Using SensorManager toListenforAccelerometerEvents218

7.2.2Custom DialogFragments218

7.2.3Drawingwith Canvas and Bitmap 219

7.2.4ProcessingMultipleTouchEventsandStoringLinesin Paths219

7.2.5Android4.4ImmersiveMode219

7.2.6 GestureDetector and SimpleOnGestureListener 219

7.2.7SavingtheDrawingtotheDevice’sGallery219

7.2.8Android4.4PrintingandtheAndroidSupportLibrary’s PrintHelper Class220

7.3BuildingtheApp’sGUI andResourceFiles220

7.3.1CreatingtheProject220

7.3.2 strings.xml 220

7.3.3 dimens.xml 221

7.3.4Menuforthe DoodleFragment 222

7.3.5 activity_main.xml Layoutfor MainActivity 223

7.3.6 fragment_doodle.xml Layoutfor DoodleFragment 223

7.3.7 fragment_color.xml Layoutfor ColorDialogFragment 224

7.3.8 fragment_line_width.xml Layoutfor LineWidthDialogFragment 226

7.3.9AddingClass EraseImageDialogFragment 227

7.4 MainActivity Class228

7.5 DoodleFragment Class229

7.6 DoodleView Class236

7.7 ColorDialogFragment Class248

7.8 LineWidthDialogFragment Class251

7.9 EraseImageDialogFragment Class255

7.10Wrap-Up256

8 AddressBook App260

ListFragment, FragmentTransactionsandthe Fragment BackStack, Threadingand AsyncTasks, CursorAdapter,SQLiteandGUIStyles

8.1Introduction261

8.2Test-Drivingthe AddressBook App264

8.3TechnologiesOverview264

8.3.1Displaying Fragmentswith FragmentTransactions265

8.3.2CommunicatingDataBetweena Fragment andaHost Activity 265

8.3.3Method onSaveInstanceState 265

8.3.4DefiningStylesandApplyingThemtoGUIComponents265

8.3.5SpecifyingaBackgroundfora TextView 265

8.3.6ExtendingClass ListFragment toCreatea Fragment That Containsa ListView 266

8.3.7ManipulatingaSQLiteDatabase266

8.3.8PerformingDatabaseOperationsOutsidetheGUIThread with AsyncTasks266

8.4BuildingtheGUIandResourceFiles266

8.4.1CreatingtheProject266

8.4.2CreatingtheApp’sClasses267

8.4.3 strings.xml 267

8.4.4 styles.xml 268

8.4.5 textview_border.xml 269

8.4.6 MainActivity’sLayout: activity_main.xml 270

8.4.7 DetailsFragment’sLayout: fragment_details.xml 270

8.4.8 AddEditFragment’sLayout: fragment_add_edit.xml 272

8.4.9Definingthe Fragments’Menus273

8.5 MainActivity Class274

8.6 ContactListFragment Class280

8.7 AddEditFragment Class287

8.8 DetailsFragment Class293

8.9 DatabaseConnector UtilityClass301

8.10Wrap-Up306

9 GooglePlayandAppBusinessIssues310

9.1Introduction311

9.2PreparingYourAppsforPublication311

9.2.1TestingYourApp312

9.2.2EndUserLicenseAgreement312

9.2.3IconsandLabels312

9.2.4VersioningYourApp313

9.2.5LicensingtoControlAccesstoPaidApps313

9.2.6ObfuscatingYourCode313

9.2.7GettingaPrivateKeyforDigitallySigningYourApp314

9.2.8Screenshots314

9.2.9PromotionalAppVideo315

9.3PricingYourApp:FreeorFee316

9.3.1PaidApps317

9.3.2FreeApps317

9.4MonetizingAppswithIn-AppAdvertising318

9.5MonetizingApps:UsingIn-AppBillingtoSellVirtualGoods319

9.6RegisteringatGooglePlay320

9.7SettingUpaGoogleWalletMerchantAccount321

9.8UploadingYourAppstoGooglePlay322

9.9Launchingthe PlayStore fromWithinYourApp323

9.10ManagingYourAppsinGooglePlay324

9.11OtherAndroidApp Marketplaces324

9.12OtherPopularMobileAppPlatforms324

9.13MarketingYourApps325

9.14Wrap-Up329

A IntroductiontoJavaApplications332

A.1Introduction333

A.2YourFirstPrograminJava:PrintingaLineofText333

A.3ModifyingYourFirstJavaProgram337

A.4DisplayingTextwith printf 339

A.5AnotherApplication:AddingIntegers339

A.6MemoryConcepts343 A.7Arithmetic344

A.8DecisionMaking:EqualityandRelationalOperators347

A.9Wrap-Up351

B IntroductiontoClasses,Objects,Methods andStrings356

B.1Introduction357

B.2DeclaringaClasswithaMethodandInstantiatinganObjectofaClass357

B.3DeclaringaMethodwithaParameter360

B.4InstanceVariables, set Methodsand get Methods363

B.5PrimitiveTypesvs.ReferenceTypes367

B.6InitializingObjectswithConstructors368

B.7Floating-PointNumbersandType double370

B.8Wrap-Up374

C ControlStatements378

C.1Introduction379

C.2Algorithms379

C.3Pseudocode380

C.4ControlStructures380

C.5 if Single-SelectionStatement381

C.6 if…else Double-SelectionStatement381

C.7 while RepetitionStatement384

C.8CaseStudy:Counter-ControlledRepetition384

C.9CaseStudy:Sentinel-ControlledRepetition388

C.10CaseStudy:Nested ControlStatements393

C.11CompoundAssignmentOperators396

C.12IncrementandDecrementOperators396

C.13PrimitiveTypes398

C.14EssentialsofCounter-ControlledRepetition399

C.15 for RepetitionStatement400

C.16ExamplesUsingthe for Statement402

C.17 do…while RepetitionStatement404

C.18 switch Multiple-SelectionStatement405

C.19 break and continue Statements412

C.20LogicalOperators412

C.21Wrap-Up415

D Methods:ADeeperLook423

D.1Introduction424

D.2ProgramModulesinJava424

D.3 static Methods, static FieldsandClass Math 425

D.4DeclaringMethodswithMultipleParameters427

D.5NotesonDeclaringandUsingMethods430

D.6Method-CallStackandActivationRecords431

D.7ArgumentPromotionandCasting431

D.8JavaAPIPackages432

Contents

D.9IntroductiontoRandom-NumberGeneration433

D.9.1ScalingandShiftingofRandomNumbers434

D.9.2Random-NumberRepeatabilityforTestingandDebugging435

D.10CaseStudy:AGameofChance;IntroducingEnumerations436

D.11ScopeofDeclarations440

D.12MethodOverloading442

D.13Wrap-Up445

E ArraysandArrayLists452

E.1Introduction453

E.2Arrays453

E.3DeclaringandCreatingArrays454

E.4ExamplesUsingArrays455

E.5CaseStudy:CardShufflingandDealingSimulation464

E.6Enhanced for Statement468

E.7PassingArraystoMethods469

E.8CaseStudy:Class GradeBook UsinganArraytoStoreGrades473

E.9MultidimensionalArrays478

E.10CaseStudy:Class GradeBook UsingaTwo-DimensionalArray482

E.11Class Arrays 488

E.12IntroductiontoCollectionsandClass ArrayList 490

E.13Wrap-Up493

F ClassesandObjects:ADeeperLook498

F.1Introduction499

F.2 Time ClassCaseStudy499

F.3ControllingAccesstoMembers503

F.4ReferringtotheCurrentObject’sMemberswiththe this Reference504

F.5 Time ClassCaseStudy:OverloadedConstructors506

F.6DefaultandNo-ArgumentConstructors512

F.7Composition513

F.8Enumerations516

F.9GarbageCollection518

F.10 static ClassMembers519

F.11 final InstanceVariables523

F.12Packages523

F.13PackageAccess524

F.14Wrap-Up524

G

Object-OrientedProgramming:Inheritance andPolymorphism527

G.1IntroductiontoInheritance528

G.2SuperclassesandSubclasses529

G.3 protected Members530

G.4RelationshipbetweenSuperclassesandSubclasses531

G.4.1CreatingandUsinga CommissionEmployee Class531

G.4.2CreatingandUsinga BasePlusCommissionEmployee Class536

G.4.3Creatinga CommissionEmployee–BasePlusCommissionEmployee InheritanceHierarchy541

G.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance HierarchyUsing protected InstanceVariables544

G.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance HierarchyUsing private InstanceVariables547

G.5Class Object 552

G.6IntroductiontoPolymorphism553

G.7Polymorphism:AnExample554

G.8DemonstratingPolymorphicBehavior555

G.9AbstractClassesandMethods558

G.10CaseStudy:PayrollSystemUsingPolymorphism559

G.10.1AbstractSuperclass Employee 560

G.10.2ConcreteSubclass SalariedEmployee 563

G.10.3ConcreteSubclass HourlyEmployee 565

G.10.4ConcreteSubclass CommissionEmployee 566

G.10.5IndirectConcreteSubclass BasePlusCommissionEmployee 568

G.10.6PolymorphicProcessing,Operator instanceof andDowncasting569

G.10.7SummaryoftheAllowedAssignmentsBetweenSuperclassand SubclassVariables574

G.11 final MethodsandClasses575

G.12CaseStudy:CreatingandUsingInterfaces576

G.12.1Developinga Payable Hierarchy577

G.12.2Interface Payable 578

G.12.3Class Invoice 579

G.12.4ModifyingClass Employee toImplementInterface Payable 581

G.12.5ModifyingClass SalariedEmployee forUseinthe Payable Hierarchy583

G.12.6UsingInterface Payable toProcess Invoicesand Employees Polymorphically585

G.13CommonInterfacesoftheJavaAPI586

G.14Wrap-Up587

H ExceptionHandling:ADeeperLook591

H.1Introduction592

H.2Example:DividebyZerowithoutExceptionHandling592

H.3Example:Handling ArithmeticExceptionsand InputMismatchExceptions 594

H.4WhentoUseExceptionHandling599

H.5JavaExceptionHierarchy599

H.6 finally Block602

H.7StackUnwindingandObtainingInformationfromanExceptionObject606

H.8Wrap-Up609

I GUIComponentsandEventHandling612

I.1Introduction613

I.2NimbusLook-and-Feel613

I.3TextFieldsandanIntroductiontoEventHandlingwithNestedClasses614

I.4CommonGUIEventTypesandListenerInterfaces620

I.5HowEventHandlingWorks621

I.6 JButton 623

I.7 JComboBox;UsinganAnonymousInnerClassforEventHandling627

I.8AdapterClasses630

I.9Wrap-Up631

J OtherJavaTopics632

J.1Introduction633

J.2CollectionsOverview633

J.3Type-WrapperClassesforPrimitiveTypes634

J.4Interface Collection andClass Collections 634

J.5Lists635

J.5.1 ArrayList and Iterator 635

J.5.2 LinkedList 637

J.5.3ViewsintoCollectionsand Arrays Method asList 640

J.6 Collections Methods642

J.6.1Method sort 642

J.6.2Method shuffle 644

J.7Interface Queue 645

J.8Sets645

J.9Maps646

J.10IntroductiontoFilesandStreams649

J.11Class File 650

J.12IntroductiontoObjectSerialization651

J.13IntroductiontoMultithreading652

J.14CreatingandExecutingThreadswiththe Executor Framework653

J.15OverviewofThreadSynchronization657

J.16ConcurrentCollectionsOverview658

J.17MultithreadingwithGUI658

J.18Wrap-Up665

K OperatorPrecedenceChart668

L PrimitiveTypes670 Index671

Preface

Buildabettermousetrap,andtheworldwillbeatapathtoyourdoor.

—RalphWaldoEmerson

Scienceandtechnologyandthevariousformsofart, allunitehumanityinasingleandinterconnectedsystem.

—ZhoresAleksandrovichMedvede

WelcometothedynamicworldofAndroidsmartphoneandtabletappdevelopmentwith theAndroidSoftwareDevelopmentKit(SDK),theJava™programminglanguage,the AndroidDevelopmentToolsIDE,andthenewandrapidlyevolvingAndroidStudio.We presentleading-edgemobilecomputingtechnologiesforstudents,instructorsandprofessionalsoftwaredevelopers.

AndroidHowtoProgram,2/e

Withthisuniquebook—thesecondeditionof theworld’sfirstAndroidcomputerscience textbook—youcanlearnAndroidevenifyoudon’tknowJavaandevenifyou’reaprogrammingnovice.Thisbookincludesacomplete,300-pageintroductiontotheJavacore programmingconceptsthatyou’llneedwhendevelopingAndroidapps.TheJavacontent isappropriateforprogrammingnovices.

AndroidHowtoProgram,2/e wasformedbymerging

•ourprofessionalbook AndroidforProgrammers:AnApp-DrivenApproach,2/e, Volume1

•additionalonlinechaptersselectedfrom AndroidforProgrammers:AnApp-Driven Approach,2/e,Volume2

•condensed,introductorycorecontentonobject-orientedJavaprogramming fromourcollegetextbook JavaHowtoProgram,9/e

•hundredsofAndroidshort-answerquestionsandapp-developmentexerciseswe createdforthisbook—mostareinthebookandmanyoftheshort-answerquestionsareinthetest-itemfileforinstructors.

WescouredtheAndroidmaterial,especiallythefullycodedAndroidapps,andenumeratedtheJavafeaturesthatyou’llneedtobuildtheseandsimilarapps.Thenwe extractedthecorrespondingJavacontentfrom JavaHowtoProgram,9/e.That’sa1500pagebook,soitwaschallengingtowhittledownthatmuchcontentandkeepitfriendly, evenforprogrammingnovices.

WhenyoustudytheAndroidcontent,you’llbethinkinglikeadeveloperfromthe start.You’regoingtostudyandbuildlotsofrealstuffandyou’llfacethekindsofchallengesprofessionaldevelopersmustdealwith.We’llpointyoutotheonlinedocumenta-

tionandforumswhereyoucanfindadditionalinformationandgetanswerstoyour questions.We’llalsoencourageyoutoread,modifyandenhanceopen-sourcecodeaspart ofyourlearningprocess.

IntendedAudiences

Thereareseveralaudiencesforthisbook. Mostcommonly,itwillbeusedinupper-level electivecollegecoursesandindustryprofessionalcoursesforpeoplefamiliarwithobjectorientedprogrammingbutwhomayormaynot knowJavaandwanttolearnAndroidapp development.

Uniquely,thebookcanalsobeusedinintroductorycourseslikeCS1,intendedfor programmingnovices.Werecommendthatschoolstypicallyofferingmanysectionsof CS1inJavaconsiderdesignatingoneortwosectionsforambitiousstudentswhohaveat leastsomepriorprogrammingexperienceandwhowanttoworkhardtolearnagood amountofJavaandAndroidinanaggressively pacedone-semestercourse.Theschools maywanttolistthecourseswith“honors”or “accelerated”designations.Thebookworks especiallywellintwo-semesterintroductoryprogrammingsequenceswheretheintroductiontoJavaiscoveredfirst.

App-DevelopmentCourses

In2007,StanfordofferedanewcoursecalledCreatingEngagingFacebookApps.Students workedinteamsdevelopingapps,someofwhich landedinFacebook’stop10,earningsome ofthestudentdevelopersmillionsofdollars.1 Thiscoursegainedwiderecognitionforencouragingstudentcreativityandteamwork. Scoresofcollegesnow offerapp-development coursesacrossmanysocialnetworkingandmobileplatformssuchasAndroidandiOS.We encourageyoutoreadtheonlinemobileapp developmentsyllabiandcheckouttheYouTube™videoscreatedbyinstructorsand studentsformanyofthesecourses.

AndroidEcosystem:Competition,Innovation,ExplosiveGrowth andOpportunities

SalesofAndroiddevicesandappdownloadshavebeengrowingexponentially.ThefirstgenerationAndroidphoneswerereleasedinOctober2008.AstudybyStrategyAnalytics showedthatbyOctober2013,Androidhad81.3%oftheglobalsmartphonemarket share,comparedto13.4%forApple,4.1%forMicrosoftand1%forBlackberry.2 AccordingtoanIDCreport,bytheendofthefirstquarterof2013Androidhad56.5%ofthe globaltabletmarketshare,comparedto39.6%forApple’siPadand3.7%forMicrosoft Windowstablets.3

TherearenowoveronebillionAndroidsmartphonesandtabletsinuse,4 andmore than1.5millionAndroiddevicesarebeingactivateddaily.5 AccordingtoIDC,Samsung

1. http://www.businessinsider.com/these-stanford-students-made-millions-taking-aclass-on-facebook-2011-5

2. http://blogs.strategyanalytics.com/WSS/post/2013/10/31/Android-Captures-Record81-Percent-Share-of-Global-Smartphone-Shipments-in-Q3-2013.aspx.

3. http://www.idc.com/getdoc.jsp?containerId=prUS24093213.

4. http://www.android.com/kitkat.

5. http://www.technobuffalo.com/2013/04/16/google-daily-android-activations-1-5-million.

istheleadingAndroidmanufacturer,accountingfornearly40%ofAndroiddeviceshipmentsinthethirdquarterof2013.

BillionsofappshavebeendownloadedfromGooglePlay™—Google’smarketplace forAndroidApps.TheopportunitiesforAndroidappdevelopersareenormous.

Fiercecompetitionamongpopularmobileplatformsandcarriersisleadingtorapid innovationandfallingprices.Competition amongthedozensofAndroiddevicemanufacturersisdrivinghardwareandsoftwareinnovationwithintheAndroidcommunity.

App-DrivenApproach

Attheheartofthebookisour app-drivenapproach—wepresentconceptsinthecontext of sevencompleteworkingAndroidapps intheprintbookandmoreonline.Webegineach oftheappchapterswithan introduction totheapp,anapp test-drive showingoneormore sampleexecutions,anda technologiesoverview.Webuildtheapp’sGUIandresourcefiles. Thenweproceedwithadetailed codewalkthrough oftheapp’ssourcecodeinwhichwe discusstheprogrammingconceptsanddemonstratethefunctionalityoftheAndroidAPIs usedintheapp.Allthesourcecodeisavailableat http://www.deitel.com/books/ AndroidHTP2 andatthebook’sCompanionWebsite http://www.pearsonhighered.com/ deitel.WerecommendthatyouhavethesourcecodeopenintheIDEasyoureadthe book.Figure1liststhebook’sappsandthekeytechnologiesweusedtobuildeach.

App Technologies

Chapter2, Welcome App TheAndroidDeveloperTools(theEclipseIDE andtheADTPlugin),visualGUIdesign,layouts, TextViews, ImageView s,accessibilityand internationalization.

Chapter3, TipCalculator App GridLayout, LinearLayout, EditText, SeekBar, eventhandling, NumberFormat anddefiningapp functionalitywithJava.

Chapter4, Twitter® Searches App SharedPreferences ,collections, ImageButton , ListView, ListActivity, ArrayAdapter,implicit intentsand AlertDialogs.

Chapter5, FlagQuiz App Fragments,menus,preferences, AssetManager, tweenedanimations, Handler, Toasts,Explicit Intents,layoutsformultipledeviceorientations.

Chapter6, CannonGame App Listeningfortouches, frame-by-frameanimation,graphics,sound,threading, SurfaceView and SurfaceHolder.

Chapter7, Doodlz App Two-dimensionalgraphics,Canvas,Bitmap, accelerometer, SensorManager,multitouch events, MediaStore,printingandImmersive Mode.

Chapter8, AddressBook App AdapterViewsand Adapters

Fig.1 | AndroidHowtoProgram appsintheprintbook.

OnlineChaptersandBookUpdates

TheCompanionWebsitecontainsadditionalapp-developmentchaptersthatintroduce propertyanimation,GooglePlaygameservices,video,speechsynthesisandrecognition, GPS,theMapsAPI,thecompass,objectserialization,Internet-enabledapps,audiorecordingandplayback,Bluetooth®,HTML5mobileappsandmore. Mostofthesechapterswillbeavailableforfall2014courses.Forthestatusoftheonlinechaptersandfor continuingbookupdates,visit

http://www.deitel.com/books/AndroidHTP2

JointheDeitelcommunitiesonFacebook® (http://www.deitel.com/deitelfan), Twitter® (@deitel),LinkedIn® (http://bit.ly/DeitelLinkedIn)Google+™ (http:// google.com/+DeitelFan),andYouTube™(http://youtube.com/user/DeitelTV)and subscribetothe Deitel ® BuzzOnline newsletter(http://www.deitel.com/newsletter/ subscribe.html).

CopyrightNoticeandCodeLicense

AlloftheAndroidcodeandAndroidappsinthebookarecopyrightedbyDeitel&Associates, Inc.ThesampleAndroidappsinthebookarelicensedunderaCreativeCommonsAttribution 3.0UnportedLicense (http://creativecommons.org/licenses/by/3.0),withtheexceptionthattheymaynotbereusedinanywayineducationaltutorialsandtextbooks,whetherin printordigitalformat.Additionally,theauthorsandpublishermakenowarrantyofanykind, expressedorimplied,withregardtotheseprogramsortothedocumentationcontainedinthis book.Theauthorsandpublishershallnotbeliableinanyeventforincidentalorconsequential damagesinconnectionwith,orarisingoutof,thefurnishing,performance,oruseoftheseprograms.You’rewelcometousetheappsinthebookasshellsforyourownapps,buildingontheir existingfunctionality.Ifyouhaveanyquestions,contactusat deitel@deitel.com.

GettinguptoSpeedinJavaandXML

TheAndroidportionofthisbookassumesthatyoualreadyknowJavaandobject-oriented programming.Ifyou’renotfamiliarwiththese,theappendicesprovideacondensed, friendlyintroductiontoJavaandtheobject-orientedprogrammingtechniquesyou’llneed todevelopAndroidapps.Ifyou’reinterestedinlearningJavainmoredepth,youmaywant tocheckoutthecomprehensivetreatmentinourtextbook JavaHowtoProgram,10/e (http://www.deitel.com/books/jhtp10).

BecauseoftheimprovedAndroiddevelopmenttools,wewereabletoeliminate almostallXMLmarkupinthisedition.Therearestilltwosmall,easy-to-understandXML filesyou’llneedtomanipulate.Ifyou’renotfamiliarwithXML,seetheseonlinetutorials:

• http://www.deitel.com/articles/xml_tutorials/20060401/XMLBasics/

• http://www.deitel.com/articles/xml_tutorials/20060401/ XMLStructuringData/

• http://www.ibm.com/developerworks/xml/newto/

• http://www.w3schools.com/xml/xml_whatis.asp

KeyFeaturesof AndroidHowtoProgram,2/e

• AndroidSDK4.3and4.4.WecovervariousnewAndroidSoftwareDevelopmentKit(SDK)4.3and4.4features.[Note: Theappsinthisbookareconfigured torunonAndroiddeviceswithAndroid4.3andhigher;however,mostappswill workin4.0andhigherbychangingtheirminimumrequiredSDK.]

• Fragments.StartingwithChapter5,weuse Fragmentstocreateandmanageportionsofeachapp’sGUI.Youcancombineseveralfragmentstocreateuserinterfacesthattakeadvantageoftabletscreensizes.Youalsocaneasilyinterchange fragmentstomakeyourGUIsmoredynamic,asyou’lldoinChapter8.

• Supportformultiplescreensizesandresolutions. Throughouttheappchapters wedemonstratehowtouseAndroid’smechanismsforautomaticallychoosingresources(layouts,images,etc.)basedonadevice’ssizeandorientation.

• Eclipse-BasedAndroidDevelopmentTools(ADT)coverageintheprintbook. ThefreeAndroidDevelopmentTools(ADT)integrateddevelopmentenvironment(IDE)—whichincludesEclipseandtheADTplugin—combinedwiththe freeJavaDevelopmentKit(JDK)provideallthesoftwareyou’llneedtocreate, runanddebugAndroidapps,exportthemfordistribution(e.g.,uploadthemto GooglePlay™)andmore.

• AndroidStudio. ThisisthepreferredIDEforthefutureofAndroidappdevelopment.BecausethisIDEisevolvingquickly,weputourdiscussionsofitonlineat:

• ImmersiveMode. Thestatusbaratthetopofthescreenandthemenubuttonsat thebottomcanbehidden,allowingyourappstofillmoreofthescreen.Users canaccessthestatusbarbyswipingdownfromthetopofthescreen,andthesystembar(withthebackbutton,homebuttonandrecentappsbutton)byswiping upfromthebottom.

• PrintingFramework. Android4.4KitKatallowsyoutoaddprintingfunctionalitytoyourapps,suchaslocatingavailableprintersoverWi-Fiorthecloud,selectingthepapersizeandspecifyingwhichpagestoprint.

• TestingonAndroidSmartphones,TabletsandtheAndroidEmulator. Forthebest app-developmentexperience,youshouldtestyourappsonactualAndroidsmartphonesandtablets.YoucanstillhaveameaningfulexperienceusingtheAndroid emulator(seetheBeforeYouBeginsection),howeverit’sprocessor-intensiveand canbeslow—particularlywithgamesthathavealotofmovingparts.InChapter1, wementionsomeAndroidfeaturesthatarenotsupportedontheemulator.

• Multimedia. TheappsintheprintbookuseabroadrangeofAndroidmultimediacapabilities,includinggraphics,images,frame-by-frameanimationandaudio.Theappsintheonlinechaptersusepropertyanimation,video,speech synthesisandspeechrecognition.

• AndroidBestPractices.WeadheretoacceptedAndroidbestpractices,pointing themoutinthedetailedcodewalkthroughs.Formoreinformation,visit http:// developer.android.com/guide/practices/index.html

•JavaContentintheAppendicesCanBeUsedWithJavaSE6orHigher. http://www.deitel.com/books/AndroidHTP2

• JavaExceptionHandling. WeintegratebasicexceptionhandlingearlyintheJava contentthenpresentarichertreatment inAppendixH;weuseexceptionhandlingthroughouttheAndroidchapters.

• Classes Arrays and ArrayList ;Collections. AppendixEcoversclass Arrays whichcontainsmethodsforperforming commonarraymanipulations—andgenericclass ArrayList—whichimplementsadynamicallyresizablearray-likedata structure.AppendixJintroducesJava’sgenericcollectionsthatareusedfrequentlyinourAndroidtreatment.

• JavaMultithreading. Maintainingappresponsivenessisakeytobuildingrobust AndroidappsandrequiresextensiveuseofAndroidmultithreading.AppendixJ introducesmultithreadingfundamentalssothatyoucanunderstandouruseof theAndroid AsyncTask classinChapter8.

• GUIPresentation. AppendixIintroducesJavaGUIdevelopment.AndroidprovidesitsownGUIcomponents,sothisappendixpresentsafewJavaGUIcomponentsandfocusesonnestedclasses andanonymousinnerclasses,whichare usedextensivelyforevent-handlinginAndroidGUIs.

WorkingwithOpen-SourceApps

Therearenumerousfree,open-sourceAndroidappsavailableonlinewhichareexcellent resourcesforlearningAndroidappdevelopment.Weencourageyoutodownloadopensourceappsandreadtheirsourcecodetounderstandhowtheywork.Throughoutthe bookyou’llfindprogrammingexercisesthataskyoutomodifyorenhanceexistingopensourceapps.Ourgoalistogiveyouhandlesoninterestingproblemsthatmayalsoinspire youtocreatenewappsusingthesametechnologies. Caution:Thetermsofopensource licensesvaryconsiderably. Someallowyoutousetheapp’ssourcecodefreelyforanypurpose,whileothersstipulatethatthecodeisavailableforpersonaluseonly—notforcreatingfor-saleorpubliclyavailableapps. Besuretoreadthelicensingagreementscarefully. Ifyouwishtocreateacommercialappbasedonanopen-sourceapp,youshouldconsiderhavinganintellectualpropertyattorneyreadthelicense;beawarethattheseattorneyschargesignificantfees.

PedagogicFeatures

SyntaxShading. Forreadability,wesyntaxshadethecode,similartoEclipse’sandAndroidStudio’suseofsyntaxcoloring.Oursyntax-shadingconventionsareasfollows:

commentsappearingray constantsandliteralvaluesappearinbolddarkergray keywordsappearinboldblack allothercodeappearsinnon-boldblack

CodeHighlighting. Weemphasizethekeycodesegmentsineachprogrambyenclosing theminlightgrayrectangles.

UsingFontsforEmphasis. Weusevariousfontconventions:

•Thedefiningoccurrencesofkeytermsappearin bold foreasyreference.

•On-screenIDEcomponentsappearin boldHelvetica (e.g.,the File menu).

•Programsourcecodeappearsin Lucida (e.g., intx=5;).

Inthisbookyou’llcreateGUIsusingacombinationofvisualprogramming(point andclick,draganddrop)andwritingcode.

WeusedifferentfontswhenwerefertoGUIelementsinprogramcodeversusGUI elementsdisplayedintheIDE:

•WhenwerefertoaGUIcomponentthatwecreateinaprogram,weplaceitsclass nameandobjectnameina Lucida font—e.g.,“ButtonsaveContactButton.”

•WhenwerefertoaGUIcomponentthat’spartoftheIDE,weplacethecomponent’stextina boldHelvetica fontanduseaplaintextfontforthecomponent’s type—e.g.,“the File menu”or“the Run button.”

Usingthe>Character. Weusethe > charactertoindicateselectingamenuitemfroma menu.Forexample,weusethenotation File>New toindicatethatyoushouldselectthe New menuitemfromthe File menu.

SourceCode. Allofthebook’ssourcecodeisavailablefordownloadfrom:

http://www.deitel.com/books/AndroidHTP2 http://www.pearsonhighered.com/deitel

ChapterObjectives. Eachchapterbeginswithalistoflearningobjectives.

Figures. Hundredsoftables,sourcecodelistingsandscreenshotsareincluded.

SoftwareEngineering.Westressprogramclarityandperformance,andconcentrateon buildingwell-engineered,object-orientedsoftware.

Self-ReviewExercisesandAnswers. Extensiveself-reviewexercises and answersareincludedforselfstudy.

ExerciseswithaCurrentFlair. We’veworkedhardtocreatetopicalAndroidapp-developmentexercises.You’lldevelopappsusingabroadarrayofcurrenttechnologies.Allofthe Androidprogrammingexercisesrequiretheimplementationofcompleteapps.You’llbe askedtoenhancetheexistingchapterapps,developsimilarapps,useyourcreativitytodevelopyourownappsthatusethechaptertechnologiesandbuildnewappsbasedonopensourceappsavailableontheInternet(andagain, besuretoreadandcomplywiththe open-sourcecode-licensetermsforeachapp).TheAndroidexercisesalsoincludeshortanswerfill-inandtrue/falsequestions.

IntheJavaexercises,you’llbeaskedtorecallimportanttermsandconcepts;indicate whatcodesegmentsdo;indicatewhat’swrongwithaportionofcode;writeJavastatements,methodsandclasses;andwritecompleteJavaprograms.

Index. Weincludeanextensiveindexforreference.Thepagenumberofthedefiningoccurrenceofeachkeyterminthebookishighlightedintheindexin bold.

SoftwareUsedin AndroidHowtoProgram,2/e

Allthesoftwareyou’llneedforthisbookisavailablefreefordownloadfromtheInternet. SeetheBeforeYouBeginsectionforthedownloadlinks.

Documentation. AlltheAndroidandJavadocumentationyou’llneedtodevelopAndroid appsisavailablefreeat http://developer.android.com and http://www.oracle.com/ technetwork/java/javase/downloads/index.html.ThedocumentationforEclipseis availableat www.eclipse.org/documentation.ThedocumentationforAndroidStudiois availableat http://developer.android.com/sdk/installing/studio.html.

InstructorResources

Thefollowingsupplementsareavailableto qualifiedcollegeinstructorsonly throughPearsonEducation’sInstructorResourceCenter(http://www.pearsonhighered.com/irc):

• PowerPoint® slides containingallthecodeandfiguresinthetext.

• TestItemFile ofshort-answerquestions.

• SolutionsManual withsolutionstotheend-of-chapter short-answerexercises for both theJavaandAndroidcontent.FortheJavacontent,solutionsareprovidedfor most oftheprogrammingexercises.

ThesuggestedAndroidapp-developmentprojectexercisesare not typical homeworkproblems.Thesetendtobe substantial projects—manyofwhich couldrequireweeksofeffort,possiblywithstudentsworkinginteams. Selected solutionsonly areprovidedfortheseprojectexercises—thesewillbeavailableon thePearsonInstructor’sResourceCenter (IRC)forfallsemester2014classes. Contactusat deitel@deitel.com ifyouhaveanyquestions.

PleasedonotwritetousrequestingaccesstothePearsonInstructor’sResourceCenter. Accessisrestrictedtoqualifiedcollegeinstructorsteachingfromthebook.Instructorsmay obtainaccess only throughtheirPearsonrepresentatives. Ifyou’renotaregisteredfaculty member,contactyourPearsonrepresentativeorvisit http://www.pearsonhighered.com/ educator/replocator/.

BeforeYouBegin

ForinformationconfiguringyourcomputersothatyoucandevelopappswithJavaand Android,seetheBeforeYouBeginsectionthatfollowsthisPreface.

Acknowledgments

ThankstoBarbaraDeitelforlonghoursdevotedtothisproject—shecreatedallofourJava andAndroidResourceCenters,andpatientlyresearchedhundredsoftechnicaldetails.

Thisbookwasacooperativeeffortbetweentheacademicandprofessionaldivisions ofPearson.Weappreciatetheguidance,wisdomandenergyofTracyJohnson,Executive Editor,ComputerScience.Tracyandherteamhandleallofouracademictextbooks. CaroleSnyderrecruitedthebook’sacademic reviewersandmanagedthereviewprocess. BobEngelhardtmanagedthebook’spublication.WeselectedthecoverartandMarta Samseldesignedthecover.

Wealsoappreciatetheeffortsand18-yearmentorshipofourfriendandprofessional colleagueMarkL.Taub,Editor-in-ChiefofthePearsonTechnologyGroup.Markandhis teamhandleallofourprofessionalbooksandLiveLessonsvideoproducts.KimBoe-

digheimerrecruitedandmanagedtheprofessionalreviewersfortheAndroidcontent.John FullermanagestheproductionofallofourDeitelDeveloperSeriesbooks.

We’dliketothankMichaelMorgano,aformercolleagueofoursatDeitel&Associates,Inc.,nowanAndroiddeveloperatImerj™,whoco-authoredthefirsteditionsofthis bookandourbook, iPhoneforProgrammers:AnApp-DrivenApproach.Michaelisan extraordinarilytalentedsoftwaredeveloper.

ReviewersoftheContentfrom AndroidHowtoProgram and AndroidforProgrammers:AnApp-DrivenApproach RecentEditions

Wewishtoacknowledgetheeffortsofourfirstandsecondeditionreviewers.Theyscrutinizedthetextandthecodeandprovidedcountlesssuggestionsforimprovingthepresentation:PaulBeusterien(Principal,Mobile DeveloperSolutions),EricJ.Bowden,COO (SafeDrivingSystems,LLC),TonyCantrell(GeorgiaNorthwesternTechnicalCollege), IanG.Clifton(IndependentContractorand AndroidAppDeveloper,DanielGalpin(AndroidAdvocateandauthorof IntrotoAndroidApplicationDevelopment),JimHathaway (ApplicationDeveloper,KelloggCompany),DouglasJones(SeniorSoftwareEngineer, FullpowerTechnologies),CharlesLasky(NagautuckCommunityCollege),EnriqueLopez-Manas(LeadAndroidArchitect,Sixt,andComputerScienceTeacherattheUniversityofAlcaláinMadrid),SebastianNykopp(ChiefArchitect,Reaktor),MichaelPardo (AndroidDeveloper,Mobiata),Ronan“Zero”Schwarz(CIO,OpenIntents),ArijitSengupta(WrightStateUniversity),DonaldSmith(ColumbiaCollege),JesusUbaldo Quevedo-Torrero(UniversityofWisconsin,Parkside),DawnWick(SouthwesternCommunityCollege)andFrankXu(GannonUniversity).

ReviewersoftheContentfrom JavaHowtoProgram RecentEditions

LanceAndersen(Oracle),SoundararajanAngusamy(SunMicrosystems),JosephBowbeer (Consultant),WilliamE.Duncan(LouisianaStateUniversity),DianaFranklin(UniversityofCalifornia,SantaBarbara),EdwardF.Gehringer(NorthCarolinaStateUniversity),HuiweiGuan(NorthshoreCommunityCollege),RicHeishman(GeorgeMason University),Dr.HeinzKabutz(JavaSpecialists.eu),PattyKraft(SanDiegoStateUniversity),LawrencePremkumar(SunMicrosystems),TimMargush(UniversityofAkron), SueMcFarlandMetzger(VillanovaUniversity),ShyamalMitra(TheUniversityofTexas atAustin),PeterPilgrim(Consultant),Manjeet Rege,Ph.D.(RochesterInstituteofTechnology),ManfredRiem(JavaChampion,Consultant,RobertHalf),SimonRitter(Oracle),SusanRodger(DukeUniversity),Amr Sabry(IndianaUniversity),JoséAntonio GonzálezSeco(ParliamentofAndalusia),SangShin(SunMicrosystems),S.Sivakumar (AstraInfotechPrivateLimited),Raghavan“Rags”Srinivas(Intuit),MonicaSweat(GeorgiaTech),VinodVarma(AstraInfotechPrivateLimited)andAlexanderZuev(Sun Microsystems).

Asyoureadthebook,we’dsincerelyappreciateyourcomments,criticismsandsuggestionsforimprovingthetext.Pleaseaddressallcorrespondenceto:

We’llrespondpromptly.Wereallyenjoyedwritingthisbook—wehopeyouenjoyreadingit! PaulDeitel

AbouttheAuthors

PaulDeitel,CEOandChiefTechnicalOfficerofDeitel&Associates,Inc.,isagraduate ofMIT,wherehestudiedInformationTechnology.HeholdstheJavaCertifiedProgrammerandJavaCertifiedDevelopercertifications,andisanOracleJavaChampion. ThroughDeitel&Associates,Inc.,hehasdeliveredhundredsofprogrammingcourses worldwidetoclients,includingCisco,IBM,Siemens,SunMicrosystems,Dell,Fidelity, NASAattheKennedySpaceCenter,theNationalSevereStormLaboratory,WhiteSands MissileRange,RogueWaveSoftware,Boeing,SunGardHigherEducation,NortelNetworks,Puma,iRobot,Invensysandmany more.Heandhisco-author,Dr.HarveyM. Deitel,aretheworld’sbest-sellingprogramming-languagetextbook/professionalbook/ videoauthors.

Dr.HarveyDeitel,ChairmanandChiefStrategyOfficerofDeitel&Associates,Inc., has50yearsofexperienceinthecomputerfield.Dr.DeitelearnedB.S.andM.S.degrees inElectricalEngineeringfromMITandaPh.D. inMathematicsfromBostonUniversity. Hehasextensivecollegeteachingexperience,includingearningtenureandservingasthe ChairmanoftheComputerScienceDepartmentatBostonCollegebeforefounding Deitel&Associates,Inc.,in1991withhisson, PaulDeitel.TheDeitels’publicationshave earnedinternationalrecognition,withtranslationspublishedinSimplifiedChinese,TraditionalChinese,Korean,Japanese,German, Russian,Spanish,French,Polish,Italian, Portuguese,Greek,UrduandTurkish.Dr.Deitelhasdeliveredhundredsofprogramming coursestocorporate,academic,governmentandmilitaryclients.

AbbeyDeitel,PresidentofDeitel&Associates,Inc.,isagraduateofCarnegieMellon University’sTepperSchoolofManagementwhereshereceivedaB.S.inIndustrialManagement.AbbeyhasbeenmanagingthebusinessoperationsofDeitel&Associates,Inc.for16 years.ShehascontributedtonumerousDeitel& Associatespublicationsand,togetherwith PaulandHarvey,istheco-authorof AndroidforProgrammers:AnApp-DrivenApproach,2/e, iPhoneforProgrammers:AnApp-DrivenApproach, Internet&WorldWideWebHowtoProgram,5/e, VisualBasic2012HowtoProgram,6/e and SimplyVisualBasic2010,5/e.

Deitel®Dive-Into®SeriesProgrammingLanguagesTraining

Deitel&Associates,Inc.,foundedbyPaulDeitelandHarveyDeitel,isaninternationally recognizedauthoringandcorporatetrainingorganization,specializingincomputerprogramminglanguages,objecttechnology,mobileappdevelopmentandInternetandweb softwaretechnology.Thecompany’strainingclientsincludemanyoftheworld’slargest companies,governmentagencies,branchesofthemilitary,andacademicinstitutions.The companyoffersinstructor-ledtrainingcoursesdeliveredatclientsitesworldwideonmajor programminglanguagesandplatforms,includingAndroidappdevelopment,ObjectiveCandiOSappdevelopment,Java™,XML®,C++,C,VisualC#®,VisualBasic®,Visual C++®,Python®,objecttechnology,Internetandwebprogrammingandagrowinglistof additionalprogrammingandsoftwaredevelopmentcourses.

Throughits37-yearpublishingpartnershipwithPrenticeHall/Pearson,Deitel& Associates,Inc.,publishes leading-edgeprogrammingcollegetextbooksandprofessional booksinprintandawiderangeofelectronicformatsand LiveLessons videocourses.Deitel &Associates,Inc.andthe authorscanbereachedat: deitel@deitel.com

Another random document with no related content on Scribd:

Prince Hatzfeld, of the Imperial party, who stands in great favor with the Kaiser, impressed upon the House that the Chancellor and not the wearer of the crown was the responsible personage in the State. Prince von Bülow, speaking on the first day of debate, declared that grave injury had been caused by the publication in the Daily Telegraph. He added that immediately on reading the article in question, as to the disastrous consequences of which he could not for a moment be in doubt, he sent in his resignation, taking upon himself full responsibility for the mistakes which had been made in handling the manuscript. And he followed this up with the following significant statement: "Gentlemen! recognition that the publication of these utterances has not in England had the effect anticipated by his Majesty the Emperor, and, on the other hand, in Germany has called forth great excitement and painful regret, will this firm conviction I have won in these sad days induce his Majesty the Kaiser in future to impose upon himself, even in his private conversations, that reserve which is indispensable to a consistent policy and to the authority of the Crown. If that were not so, neither I nor any of my successors could accept responsibility for it."

Proposals of amendment to the Constitution, carrying such ministerial responsibility into the fundamental law, were advocated without success; but the unwritten constitution which public opinion moulds slowly in every country took a notable shaping from these debates.

For some time the Emperor was very silent, and kept himself unusually retired. Having occasion to speak publicly at Berlin on the 21st of November, when the centennial of the formation of the City Council was celebrated, it was reported that "Prince von Bülow stepped forward and impressively handed him a printed sheet," from which, contrary to his custom, he read his remarks.

GERMANY: A. D. 1908-1909.

Attempted Reform of Imperial Finance and its Defeat. Breaking of Chancellor Bülow’s "Bloc" in the Reichstag by the Government’s project of New Taxes.

Triumph of the Agrarian Interests in renewed Coalition with the Center.

Resignation of Chancellor Bülow. His successor.

Expenditure outrunning income from year to year thanks mainly to the burden of army and navy with deficits made good by loans, mortgaging the future in an ever-growing public debt, had forced the Government, in 1908, to a resolution, not that the imperial expenditure on armament must be cut down, but that imperial taxation must be increased.

{296}

The Governments of the Federated States, which are directly represented, as such, in the Federal Council, were assenting parties to this conclusion, and the resulting measure was regarded, in all the proceedings which followed, as emanating essentially from that senatorial branch of the Parliament of the Empire.

Preparatory to the undertaking, a new Minister of Finance, Herr Reinhold Sydow, was brought into office, and early in November, 1908, he submitted to the Reichstag a bill providing for new taxes that were estimated to add 500,000,000 marks ($125,000,000) yearly to the Treasury of the Empire. The scheme included an extended and augmented inheritance tax, new methods of deriving revenue from spirits and tobacco, added excise duties on beer and bottled still wines, taxes on electricity, gas, advertisements, etc. The bill went to the Finance Committee of the Reichstag and developed there, during the next five months, an antagonism of class interests, and consequently of parties, which completely shattered the "bloc," or coalition, which Chancellor Bülow had contrived to organize in 1906 for the support of his administration. The

proposed new inheritance tax or death duty was especially obnoxious to the land-owning classes, the agrarian core of German conservatism, and no influence from the Government could save it from being stifled in their hands. Other oppositions were rallied against the proposals which touched spirits, tobacco, electricity, gas, and newspaper advertisements, and by the 20th of March, 1909, it was known that the Finance Committee had rejected or would reject all but about one-fifth of the new taxation which the Government and the Federal Council claimed from it.

A month later the Government signified its abandonment of a present expectation, at least, of financial reform, by inviting subscriptions to a fresh loan. The budget wrangle in Committee went on, however, until the 13th of May, when the National-Liberals, the Radicals, and the Socialists of the Committee withdrew from it, the Chairman, Herr Paasche, a National-Liberal, resigning, refusing to take any further part in proceedings which they wholly disapproved. This left the Conservatives, the Center or Clerical party, and the Poles, who seem to have practically organized an opposition "bloc," which proceeded to frame a budget on entirely different lines from that which the Government desired, one of its contemplated features being a tax on purchases and sales of stocks. On the 18th of May the Reichstag was adjourned until the 15th of June, and a month of rest from the controversy was enjoyed.

When the Reichstag reassembled the Government laid before it several proposals of taxes to be substituted for those which the Committee had rejected. Inheritance taxation was still prominent in the revised scheme, but considerably modified in its range and reduced in productiveness. With it went an extensive readjustment of stamp duties, applied to bonds, stock certificates, transfers of real estate, bills and checks and a tax on policies of fire insurance. This revised budget of additions to the Imperial revenue was estimated to yield

about $35,000,000. It fared no better than the original proposals of the Government. A week after its introduction the Reichstag adopted the tax on securities (called the Cotierungssteuer) which the Government disapproved, and on the 24th of June it rejected the new inheritance tax bill, by 194 votes to 186, the minority being composed of National-Liberals, Radicals and Socialists, with a few from the Conservative side. On the next day, rumors of the intended resignation of Prince Bülow were checked by the publication of the following semi-official statement:

"Prince von Bülow will remain as chancellor of the empire. The Reichstag will not be dissolved. The chancellor holds that his duty is to be in accord with the conviction of the Federal Council of the necessity to bring about the passage of a taxation measure, but with the exclusion therefrom of duties on stock transfers, the output of the grain mills, and the exports of coal. Financial reform must now come into operation. What the chancellor will do after this has been accomplished is his personal affair."

Nevertheless, it was made known on the 27th that the Chancellor had offered his resignation to the Emperor, who had declined to accept it, pointing out "that in the unanimous conviction of the Federal Governments the early achievement of finance reform is a vital question for the internal welfare of the Empire, as well as for its position in relation to foreign countries. In the circumstances he could not take into closer consideration the fulfilment of Prince Bülow’s wish to be relieved of his offices until the labours for the reform of the Imperial finances should have produced a result of a positive kind which the Federal Governments could accept." To this statement there was added, semi-officially, next day, the following: "Subject to the rejection of those taxation proposals which would be injurious to the general interest, and therefore impossible of acceptance by the Federal Governments, the Imperial Chancellor was unwilling not to

comply with the Emperor’s desire. Nevertheless, having regard to the political development which was manifested by the division on the inheritance tax, he is irrevocably resolved to retire from office immediately after the accomplishment of finance reform."

Then followed negotiations with the Conservative-Clerical majority now fully in control of the Reichstag, the Government yielding step by step, and the Federal Council coming openly into the management of the negotiations, the Chancellor falling into the background, and waiting only for permission to lay his office down. In the resulting budget of new taxes there was very little saved of the "financial reform" which the Federal Council and the Chancellor had undertaken to introduce. On most points the land-owners had their way. The character and effect of the legislation accomplished in the early days of July were described thus by a Berlin correspondent of the New York Evening Post, who wrote on the 11th of the month:

"The leitmotif of the bill is that property shall be protected and industry shall pay. Even on the reckoning of the new majority the ratio between indirect and direct taxation in the scheme is as 14 to 34, but in reality property comes off far better. … The large land-owners will not be hit at all. The only tax that could touch them to any appreciable extent is the stamp duty on transfers of real estate.

{297}

But the remedy lies in their hands; they need not sell, and, in any event, of the $10,000,000 at which the returns are estimated only $1,250,000 at most falls on landed property. If the spirits bounty to be paid by the Government to the spirit distilleries (which are in agrarian hands) is set against this sum, it will be seen that the agrarians do not only not suffer, but net a profit of some ten millions of dollars. Most of all it is the consuming classes that are the victims of the new majority's taxation proposals. Every cup of coffee, the

staple nourishment of the German workingman’s family, every cup of tea, every glass of beer and schnapps, the staple refreshment of the German workingman, will cost more, the total sum to be derived from these sources reaching $54,250,000, which, with the duty on the poor man’s cigar, amounts to over $60,000,000. Adding to this 30 per cent. for the increase in the middleman’s prices, the total burden of the consuming classes reaches over $80,000,000, or an increase of $7.50 on the workingman’s household expenses a year."

On the 13th of July the session of the Reichstag was closed by Imperial decree. On the 14th the following announcement appeared in the Imperial Gazette: "His Majesty the Emperor and King has been graciously pleased to accede to the request of the Imperial Chancellor, the President of the Ministry, and Minister for Foreign Affairs, Prince Bülow, to be relieved of his offices, and has conferred upon him the High Order of the Black Eagle with brilliants. His Majesty has been graciously pleased to appoint Dr. von Bethmann-Hollweg, Secretary of State for the Interior, Minister of State, to be Imperial Chancellor, President of the Ministry, and Minister for Foreign Affairs." Herr Sydow now resigned from the secretaryship of the Imperial Treasury, and was made Prussian Minister of Commerce, in place of Herr Delbruck, who succeeded the new Chancellor as "Imperial Secretary of State for the Interior and representative of the Imperial Chancellor." Herr Sydow’s place in the department of the Imperial Treasury was taken by Herr Wermuth.

GERMANY: A. D. 1908-1909 (September-May). The Casablanca Incident and its Arbitration at The Hague. Friendly Agreement with France.

See (in this Volume)

MOROCCO: A. D. 1907-1909.

GERMANY: A. D. 1909.

Accelerated Naval Construction. Excitement in Great Britain. Parliamentary Debates.

See (in this Volume) WAR, THE PREPARATIONS FOR: NAVAL.

GERMANY: A. D. 1909. Extent of Trade Unionism.

See (in this Volume) LABOR ORGANIZATION: GERMANY.

GERMANY: A. D. 1909. Proposed Amendments of the System of Workingmen’s Insurance.

See (in this Volume) POVERTY, THE PROBLEMS OF: PENSIONS; also, LABOR PROTECTION: ACCIDENT AND SICKNESS INSURANCE.

GERMANY: A. D. 1909 (January). Rejection of Proposed Reforms of the Elective Franchise in Prussia.

See (in this Volume) ELECTIVE FRANCHISE: PRUSSIA.

GERMANY: A. D. 1909 (April). Economic Conditions. Gain of Fifteen Years in National Wealth. Increased Cost of Living. Diminished Savings. Check on the Overcrowding of Towns.

A report by the British Consul-General on the trade and commerce of the consular district of Frankfort-on-the-Main for

the year ending April 30, 1909, gave the following items of interest touching general economic conditions of the year:

Early in 1909 the national wealth of Germany, which had been estimated at 220,000,000,000 marks 15 years ago, was estimated to have reached 350,000,000,000 marks i. e., an increase of 59 per cent. in half a generation.

"The cheapening of all manufactured commodities in comparison with the price they had reached during the end of the boom has failed until now, in spite of an unprecedented supply of cash, because the development which had taken place behind the wall of protection the system of syndication has killed free competition at home and has unduly raised the cost of the raw material needed by the finishing industries. The agricultural protection as well as the industrial has, moreover, increased the cost of living and has narrowed down the margin of profit which might have been used like a safety valve for reductions of price to revive trade at home or facilitate competition abroad. Syndication and protection have in fact combined to deprive German manufacture of that elastic cheapening power which ought chiefly to revive trade during the period succeeding a commercial high tide. At the same time the increased protection of the home market has admittedly rendered foreign markets more difficult for the German manufacturer."

See (in this Volume) LABOR REMUNERATION: WAGES, &C.

GERMANY: A. D. 1909 (September).

Speech of the Emperor on the Pride of his Subjects in "the Game of War."

See (in this Volume) WAR, THE PREPARATIONS FOR: MILITARY.

GERMANY: A. D. 1909 (September).

Latest Statistics of the Social Democratic Party.

See (in this Volume)

SOCIALISM: GERMANY.

GERMANY: A. D. 1909 (October-December).

Socialist Gains in By-elections, etc.

Changed relations between Parties and the Government.

Several by-elections for the Reichstag and elections to the diets of Saxony and Baden in these months showed somewhat startling gains for the Socialists. In the Saxon Diet they won 25 seats, whereas in the late chamber, elected in 1907, they had held but 1. Both the Conservatives and the National Liberals were losers in the contest, the former most heavily. The Radicals shared a few of the gains. In the Baden Diet the Socialist gain was 8. At a by-election in one of the Brandenburg divisions the Socialists increased their vote by more than a thousand.

The Reichstag was reopened by the Emperor on the 30th of November. On the organization of the House, Dr. Herman S. Paasche, National Liberal, declined election as Second Vice-President, stating that the National-Liberal party had decided unanimously not to accept office in the reorganization of the House. The Imperial party, or free Conservatives, also declined to take part in the organization, while the Radicals went so far as to decide that they would cast blank votes. These three parties are determined to place the full responsibility for the coming legislation upon the German Conservatives and Clericals.

{298}

This new attitude of parties, as one side of the sequence to the dissolution of the bloc of the past two years, and to the

retirement of Chancellor Bülow, was responded to most appositely on the side of the Government by the new Imperial Chancellor, Dr. von Bethmann Hollweg, when he made his first speech in that capacity to the Reichstag, December 9th. In not many words he made it plain that the Imperial Government’s policy now was "to stand aloof from parties and groups of parties; in short, that the government of Germany was not a government by party. Governmental measures would be submitted to the Reichstag for adoption, but he was not disposed to define the constellation of parties which, he thought, would support these measures. The recent political crisis over the taxation bill had made no change in German institutions, he continued. Radicalism strove to divide all Germany into two political camps, but the existence of such a dualism was a fiction devised for party objects. It could not contribute to the sound development of the country for every proposal to be classified as either radical or reactionary. Germany, the chancellor affirmed, needed continuous and steady policies, both at home and abroad, to satisfy the people to the end that their work, either material or intellectual, might be undisturbed by disorders or experiments." His words in part were as follows:

"As decidedly as the separate parties have ever refused, and still refuse, to be Government parties and I personally can thoroughly understand it so little will a Government in Germany ever be able to be a party Government. With the difficulties which arise from this fact every German statesman has had to fight, and in this relation of things, which is historic and based upon the peculiarity of our party life and of our State institutions, the last crisis has altered nothing whatever. I do not shut my eyes," continued the Chancellor, "to the excitement of party politics which pervades the country." But he believed that there were wide circles of the German people who did not wish to live permanently on political excitement and recrimination. "What our people desires in the first place is not to be disturbed in its

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.