Android Database Best Practices - Pearsoncmg

Transcription

AndroidDatabase BestPractices

About the AndroidDeep Dive SeriesZigurd Mednieks, Series EditorThe Android Deep Dive Series is for intermediate and expert developers who useAndroid Studio and Java, but do not have comprehensive knowledge of Android systemlevel programming or deep knowledge of Android APIs. Readers of this series want tobolster their knowledge of fundamentally important topics.Each book in the series stands alone and provides expertise, idioms, frameworks, andengineering approaches. They provide in-depth information, correct patterns and idioms,and ways of avoiding bugs and other problems. The books also take advantage of newAndroid releases, and avoid deprecated parts of the APIs.About the Series EditorZigurd Mednieks is a consultant to leading OEMs, enterprises, and entrepreneurial ventures creating Android-based systems and software. Previously he was chief architect at D2 Technologies, a voice-over-IP (VoIP) technology provider, and a founder ofOpenMobile, an Android-compatibility technology company. At D2 he led engineeringand product definition work for products that blended communication and social mediain purpose-built embedded systems and on the Android platform. He is lead author of Programming Android and Enterprise Android.

AndroidDatabase BestPractices Adam StroudBoston Columbus Indianapolis New York San Francisco Amsterdam Cape TownDubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico CitySão Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and thepublisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.The author and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors oromissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.For information about buying this title in bulk quantities, or for special sales opportunities(which may include electronic versions; custom cover designs; and content particular toyour business, training goals, marketing focus, or branding interests), please contact ourcorporate sales department at corpsales@pearsoned.com or (800) 382-3419.For government sales inquiries, please contact governmentsales@pearsoned.com.For questions about sales outside the U.S., please contact intlcs@pearson.com.Visit us on the Web: informit.com/awLibrary of Congress Control Number: 2016941977Copyright 2017 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protectedby copyright, and permission must be obtained from the publisher prior to any prohibitedreproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. For information regardingpermissions, request forms and the appropriate contacts within the Pearson EducationGlobal Rights & Permissions Department, please visit www.pearsoned.com/permissions/.The following are registered trademarks of Google: Android , Google Play .Google and the Google logo are registered trademarks of Google Inc., used withpermission.The following are trademarks of HWACI: SQLite, sqlite.org, HWACI.Gradle is a trademark of Gradle, Inc.Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.Square is a registered trademark of Square, Inc.Facebook is a trademark of Facebook, Inc.Java and all Java-based trademarks and logos are trademarks or registered trademarks ofOracle and/or its affiliates.MySQL trademarks and logos are trademarks or registered trademarks of Oracle and/orits affiliates.The following are registered trademarks of IBM: IBM, IMS, Information ManagementSystem.PostgreSQL is copyright 1996-8 by the PostgreSQL Global Development Group, and isdistributed under the terms of the Berkeley license.Some images in the book originated from the sqlite.org and used with permission.Twitter is a trademark of Twitter, Inc.ISBN-13: 978-0-13-443799-6ISBN-10: 0-13-443799-3Text printed in the United States on recycled paper at RR Donnelleyin Crawfordsville, Indiana.First printing, July 2016PublisherMark L. TaubExecutive EditorLaura LewinDevelopment EditorMichael ThurstonManaging EditorSandra SchroederFull-Service ProductionManagerJulie B. NahilProject EditorcodeMantraCopy EditorBarbara WoodIndexerCheryl LenserProofreadercodeMantraEditorial AssistantOlivia BasegioCover DesignerChuti PrasertsithCompositorcodeMantra

vTo my wife, Sabrina, and my daughters, Elizabeth and Abigail.You support, inspire, and motivate me in everything you do.v

This page intentionally left blank

Contents in BriefPreface  xvAcknowledgments  xixAbout the Author  xxi1Relational Databases  12An Introduction to SQL  173An Introduction to SQLite  394SQLite in Android  475Working with Databases in Android  796Content Providers  1017Databases and the UI  1378Sharing Data with Intents  1639Communicating with Web APIs  17710Data Binding  231Index  249

This page intentionally left blank

ContentsPreface  xvAcknowledgments  xixAbout the Author  xxi1 Relational Databases1History of Databases 1Hierarchical Model2Network Model 2The Introduction of the Relational Model 3The Relational Model 3Relation 3Properties of a Relation 5Relationships 6Relational Languages 9Relational Algebra 9Relational Calculus 13Database Languages 14ALPHA 14QUEL 14SEQUELSummary14152 An Introduction to SQL17Data Definition Language 17Tables 18Indexes 20Views 23Triggers 24Data Manipulation Language 28INSERT 28UPDATE 30DELETE 31Queries32ORDER BYJoins 34Summary3732

xContents3 An Introduction to SQLite39SQLite Characteristics 39SQLite Features 39Foreign Key Support 40Full Text Search 40Atomic Transactions 41Multithread Support 42What SQLite Does Not Support 42Limited JOIN Support 42Read-Only Views42Limited ALTER TABLE Support 43SQLite Data Types 43Storage Classes 43Type Affinity44Summary 444 SQLite in Android47Data Persistence in Phones 47Android Database API47SQLiteOpenHelperSQLiteDatabase4757Strategies for Upgrading Databases 58Rebuilding the Database 58Manipulating the Database 59Copying and Dropping Tables 59Database Access and the Main Thread 60Exploring Databases in Android 61Accessing a Database with adb 61Using Third-Party Tools to Access AndroidDatabases 73Summary 775 Working with Databases in AndroidManipulating Data in Android 79Inserting Rows into a Table 80Updating Rows in a Table 83Replacing Rows in a Table 85Deleting Rows from a Table 8679

ContentsTransactions 87Using a Transaction 87Transactions and Performance 88Running Queries 89Query Convenience Methods 89Raw Query Methods91Cursors 91Reading Cursor Data 91Managing the Cursor 94CursorLoader94Creating a CursorLoader 94Starting a CursorLoader 97Restarting a CursorLoader 98Summary996 Content Providers101REST-Like APIs in Android101Content URIs 102Exposing Data with a Content Provider 102Implementing a Content Provider 102Content Resolver 108Exposing a Remote Content Provider toExternal Apps 108Provider-Level Permission 109Individual Read/Write Permissions 109URI Path Permissions109Content Provider Permissions 110Content Provider Contract 112Allowing Access from an External App 114Implementing a Content Provider 115Extending android.content.ContentProvider 115insert() 119delete() 120update() 122query() 124getType() 130xi

xiiContentsWhen Should a Content Provider Be Used? 132Content Provider Weaknesses 132Content Provider Strengths 134Summary 1357 Databases and the UI137Getting Data from the Database to the UI137Using a Cursor Loader to Handle Threading 137Binding Cursor Data to a UI 138Cursors as Observers 143registerContentObserver(ContentObserver) 143registerDataSetObserver(DataSetObserver) 144unregisterContentObserver(ContentObserver) 144unregisterDataSetObserver(DataSetObserver) 144setNotificationUri(ContentResolver,Uri uri) 145Accessing a Content Provider from an Activity 145Activity Layout145Activity Class Definition147Creating the Cursor Loader 148Handling Returned Data 149Reacting to Changes in Data 156Summary 1618 Sharing Data with Intents163Sending Intents 163Explicit Intents 163Implicit Intents 164Starting a Target Activity164Receiving Implicit Intents 166Building an Intent 167Actions 168Extras 168Extra Data Types 169What Not to Add to an Intent 172ShareActionProvider173Share Action Menu 174Summary 175

Contents9 Communicating with Web APIs177REST and Web Services 177REST Overview177REST-like Web API Structure 178Accessing Remote Web APIs 179Accessing Web Services with StandardAndroid APIs 179Accessing Web Services with Retrofit 189Accessing Web Services with Volley 197Persisting Data to Enhance User Experience 206Data Transfer and Battery Consumption 206Data Transfer and User Experience 207Storing Web Service Response Data 207Android SyncAdapter Framework207AccountAuthenticator 208SyncAdapter 212Manually Synchronizing Remote Data 218A Short Introduction to RxJava218Adding RxJava Support to Retrofit 219Using RxJava to Perform the SyncSummary22222910 Data Binding231Adding Data Binding to an Android Project 231Data Binding Layouts232Binding an Activity to a Layout 234Using a Binding to Update a View 235Reacting to Data Changes 238Using Data Binding to Replace Boilerplate Code 242Data Binding Expression Language 246Summary247Index  249xiii

This page intentionally left blank

PrefaceThe explosion in the number of mobile devices in all parts of the word has led to anincrease in both the number and complexity of mobile apps. What was once considereda platform for only simplistic applications now contains countless apps with considerablefunctionality. Because a mobile device is capable of receiving large amounts of data frommultiple data sources, there is an increasing need to store and recall that data efficiently.In traditional software systems, large sets of data are frequently stored in a database thatcan be optimized to both store the data as well as recall the data on demand. Androidprovides this same functionality and includes a database system, SQLite. SQLite providesenough power to support today’s modern apps and also can perform well in the resourceconstrained environment of most mobile devices. This book provides details on howto use the embedded Android database system. Additionally, the book contains advice inspired by problems encountered when writing “real-world” Android apps.Who Should Read This BookThis book is written for developers who have at least some experience with writingAndroid apps. Specifically, an understanding of basic Android components (activities, fragments, intents, and the application manifest) is assumed, and familiarity with theAndroid threading model is helpful.At least some knowledge of relational database systems is also helpful but is not necessarily a prerequisite for understanding the topics in this book.How This Book Is OrganizedThis book begins with a discussion of the theory behind relational databases as well assome history of the relational model and how it came into existence. Next, the discussionmoves to the Structured Query Language (SQL) and how to use SQL to build a databaseas well as manipulate and read a database. The discussion of SQL provides some details onAndroid specifics but generally discusses non-Android-specific SQL.From there, the book moves on to provide information on SQLite and how it relatesto Android. The book also covers the Android APIs that can be used to interact with adatabase as well as some best practices for database use.With the basics of database, SQL, and SQLite covered, the book then moves into solving some of the problems app developers often face while using a database in Android. Topics such as threading, accessing remote data, and displaying data to the user are covered. Additionally, the book presents an example database access layer based on a content provider.

xviPrefaceFollowing is an overview of each of the chapters: Chapter 1, “Relational Databases,” provides an introduction to the relational database model as well as some information on why the relational model is morepopular than older database models.Chapter 2, “An Introduction to SQL,” provides details on SQL as it relates to databases in general. This chapter discusses the SQL language features for creatingdatabase structure as well as the features used to manipulate data in a database.Chapter 3, “An Introduction to SQLite,” contains details of the SQLite databasesystem, including how SQLite differs from other database systems.Chapter 4, “SQLite in Android,” discusses the Android-specific SQLite details suchas where a database resides for an app. It also discusses accessing a database fromoutside an app, which can be important for debugging.Chapter 5, “Working with Databases in Android,” presents the Android API forworking with databases and explains how to get data from an app to a database andback again.Chapter 6, “Content Providers,” discusses the details around using a content provider as a data access mechanism in Android as well as some thoughts on whento use one.Chapter 7, “Databases and the UI,” explains how to get data from the local databaseand display it to the user, taking into account some of the threading concerns thatexist on Android.Chapter 8, “Sharing Data with Intents,” discusses ways, other than using contentproviders, that data can be shared between apps, specifically by using intents.Chapter 9, “Communicating with Web APIs,” discusses some of the methods andtools used to achieve two-way communication between an app and a remoteWeb API.Chapter 10, “Data Binding,”

Android specifics but generally discusses non-Android-specific SQL. From there, the book moves on to provide information on SQLite and how it relates to Android. The book also covers the Android APIs that can be used to interact with a database as well as some best practices for database use.