
C o mm u n i t y E x p e r i e n c e D is t il l e d Android SQLite Essentials Develop Android applications with one of the most widely used database engines,SQLite Sunny Kumar Aditya Vikash Kumar Karn PACKT]open source www.allitebooks.com
www.allitebooks.com

Android SQLite Essentials Develop Android applications with one of the most widely used database engines,SQLite Sunny Kumar Aditya Vikash Kumar Karn [PACKT] open source为 community experience distilled PUBLISHING BIRMINGHAM-MUMBAI www.allitebooks.com
Android SQLite Essentials Develop Android applications with one of the most widely used database engines, SQLite Sunny Kumar Aditya Vikash Kumar Karn BIRMINGHAM - MUMBAI www.allitebooks.com

Android SQLite Essentials Copyright2014 Packt Publishing All rights reserved.No part of this book may be reproduced,stored in a retrieval critical articles or reviews. Every effort has been made in the preparation of this book to ensure th accuracy old e m on presen lied.N rPackt will be held liable fo nage caused or alleged to be caused directly or indirectly by this book. n about all of the oducts mentioned in this bo of capitals. uihing amot thaals First published:August 2014 Production reference:1200814 Published by Packt Publishing Ltd. Livery Place m时2UK ISBN978-1-78328-295-1 www.packtpub.com Cover image by Pratyush Mohanta(tysoncinematicsegmail.com) www.allitebooks.com
Android SQLite Essentials Copyright © 2014 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2014 Production reference: 1200814 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78328-295-1 www.packtpub.com Cover image by Pratyush Mohanta (tysoncinematics@gmail.com) www.allitebooks.com

Credits Authors Project Coordinator Sunny Kumar Aditya Kranti Berde Vikash Kumar Karn Reviewers Amey Haldankar Joanna McMahon Gaurav Maru Commissioning Editor Mariammal Chettiya Pramila Balan Rekha Nair Graphics Ronak Dhruv Content Development Editor Production Coordinator Ruchita Bhansali Saiprasad Kadam Technical Editors Cover Work Dennis John Saiprasad Kadam Gaurav Thingalaya Copy Editors Roshni Banerjee Gladson Monteiro Adithi Shetty www.allitebooks.com
Credits Authors Sunny Kumar Aditya Vikash Kumar Karn Reviewers Amey Haldankar Gaurav Maru Commissioning Editor Pramila Balan Acquisition Editor Nikhil Karkal Content Development Editor Ruchita Bhansali Technical Editors Dennis John Gaurav Thingalaya Copy Editors Roshni Banerjee Gladson Monteiro Adithi Shetty Project Coordinator Kranti Berde Proofreaders Simran Bhogal Joanna McMahon Indexers Mariammal Chettiyar Rekha Nair Graphics Ronak Dhruv Production Coordinator Saiprasad Kadam Cover Work Saiprasad Kadam www.allitebooks.com

About the Authors Sunny Kumar Aditya has been working on the Android platform for the past 4 years.His tryst with Android began with his college project,and he continued with his work in R&D at HCL Infosystems Ltd.Sunny loves to stay up to date with the latest trends and practices in Android development.Apart from building Android applications,he writes at wwdeamHe is currently the head of Android development at Yamunix I would like to thank Packt Publishing for this opportunity and my family as well as friends for their support. r coded is and an ECE love sh Kumar Kanare developmg the sort ent field. xploring Android. and help nev uch as movtan can be found on the Play Stor ng a I would like to thank my friends and family for their support during the course of writing this book. www.allitebooks.com
About the Authors Sunny Kumar Aditya has been working on the Android platform for the past 4 years. His tryst with Android began with his college project, and he continued with his work in R&D at HCL Infosystems Ltd. Sunny loves to stay up to date with the latest trends and practices in Android development. Apart from building Android applications, he writes at www.deadmango.com. He is currently the head of Android development at Yamunix. I would like to thank Packt Publishing for this opportunity and my family as well as friends for their support. Vikash Kumar Karn is an IIIT Allahabad alumnus and an ECE student whose love for code drove him towards the software development field. He has worked with leading multinationals and is currently working at Samsung Research Institute, Bangalore, exploring Android. Vikash likes to learn the intricacies of the Android framework and help newcomers in this field. Some of his applications, such as Movtan Fishing and Compare Pictures, can be found on the Play Store. I would like to thank my friends and family for their support during the course of writing this book. www.allitebooks.com

About the Reviewers Amey Haldankar is an Android enthusiast hooked on the platform since its early with a in Co rin m GIT,Belgau Amey has been working on the platform for the past 3 vears develon eral pplications for major clients such as Domino's,Galatsaray.HCL and Nokia. a note of thanks to the publishing house for considering me for the role of a reviewer for Android SQLite Essentials. gauray maru has a bachelor's des ee in Com uters from Shah Anchor Kutchhi Engineering College since 2011.he has been workingan Android application he U largest bookseller(a Fortune 500 company).He drinks,eats,and sleeps Android. You can contact him at gauravimaru@gmail.com. friends,colleagues,and Packt ully.Cheers! www.allitebooks.com
About the Reviewers Amey Haldankar is an Android enthusiast hooked on the platform since its early days. Equipped with a degree in Computer Science Engineering from GIT, Belgaum, he is working for HCL Infosystems Ltd. as a Senior Software Engineer. Amey has been working on the platform for the past 3 years developing several applications for major clients such as Domino's, Galatsaray, HCL, and Nokia. A note of thanks to the publishing house for considering me for the role of a reviewer for Android SQLite Essentials. Gaurav Maru has a Bachelor's degree in Computers from Shah & Anchor Kutchhi Engineering College. Since 2011, he has been working as an Android application developer at various organizations, including India's largest retail sector company. Gaurav has developed various apps, including the one developed for the USA's largest bookseller (a Fortune 500 company). He drinks, eats, and sleeps Android. You can contact him at gaurav1maru@gmail.com. I would like to thank my family, friends, colleagues, and Packt Publishing, who helped me pull this one off successfully. Cheers! www.allitebooks.com

www.PacktPub.com Support files,eBooks,discount offers and more You might want to visit www.Packt Pub.com for support files and downloads related to your book. service@packtpub.com for more details. PACKTLiB http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions?PacktLib is Packt's online digital book library.Here,you can access,read and search across Packt's entire library of books. Why Subscribe? ully searchable across every book published by Packt Copy and paste,print and bookmark content On demand and accessible via web browser Free Access for Packt account holders immediate access. www.allitebooks.com
www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. www.allitebooks.com

Table of Contents Preface Chapter 1:Enter SQLite Why SQLite? The SQLite architecture 8 The SQLite interface The SQL compiler Thesaleoac en 2SOL8品mSnfdamontals Lite TDeBoeandaiag atype SQLite in Android SOLite version Database packages APIs 9022233456663223 Summary Chapter 2:Connecting the Dots Building blocks base handle r and queries Building the Create e query 23263025 Building the Insert query www.allitebooks.com
Table of Contents Preface 1 Chapter 1: Enter SQLite 5 Why SQLite? 6 The SQLite architecture 8 The SQLite interface 8 The SQL compiler 8 The virtual machine 9 The SQLite backend 9 A quick review of database fundamentals 9 What is an SQLite statement? 10 The SQLite syntax 12 Datatypes in SQLite 12 Storage classes 12 The Boolean datatype 13 The Date and Time datatype 13 SQLite in Android 14 SQLite version 15 Database packages 16 APIs 16 The SQLiteOpenHelper class 16 The SQLiteDatabase class 19 ContentValues 22 Cursor 22 Summary 23 Chapter 2: Connecting the Dots 25 Building blocks 26 A database handler and queries 30 Building the Create query 32 Building the Insert query 35 www.allitebooks.com

Table of Contents Building the Delete query Building the Update query 41 Connecting the Ul and database Summary Chapter 3:Sharing is Caring 49 What is a content ovider? Creating a content provider Understanding content URIs Declaring our contract class Creating UriMatcher definitions Implementing the core methods Initializing the provider through the onCreate()method Querying reco ords thro ugh the query()met 00 through the insert()method ing recor thro he upc et)m eting rec s through e retu thod ype or d nrough the getType()method 5959624 a pr est ing a content prov Chapter 4:Thread Carefully Loading data with CursorLoader 73 Loaders Loader API's summary Using CursorLoader 55 Data security 8 ContentProvider and permissions Encrypting critical data General tips anc libraries Upgrading a dat Database minus SQL stat nents Shipping with a prepopulated database 32566803 mmary Index 95 www.allitebooks.com
Table of Contents [ ii ] Building the Delete query 40 Building the Update query 41 Connecting the UI and database 43 Summary 48 Chapter 3: Sharing is Caring 49 What is a content provider? 50 Using existing content providers 51 What is a content resolver? 51 Creating a content provider 54 Understanding content URIs 55 Declaring our contract class 56 Creating UriMatcher definitions 58 Implementing the core methods 59 Initializing the provider through the onCreate() method 59 Querying records through the query() method 59 Adding records through the insert() method 61 Updating records through the update() method 61 Deleting records through the delete() method 62 Getting the return type of data through the getType() method 63 Adding a provider to a manifest 64 Using a content provider 64 Summary 72 Chapter 4: Thread Carefully 73 Loading data with CursorLoader 73 Loaders 74 Loader API's summary 75 Using CursorLoader 75 Data security 80 ContentProvider and permissions 80 Encrypting critical data 82 General tips and libraries 85 Upgrading a database 86 Database minus SQL statements 87 Shipping with a prepopulated database 90 Summary 93 Index 95 www.allitebooks.com

Preface Android is probably the ebuzzword of this decade.In a sh the majority( ne hand market. id is ds to her skill sets as well should have.SQLite database in applications is the heart of a data-centric product and key to building great products.Understanding SQLite and implementing the Android database can be a steep learning curve for some people.Concepts such as content rs and loa are mo om men And d SQLite ups dev pers with to ata ase-ba ved in the industr Let us start our jo eed What this book covers Chapter 1,Enter SQLite,provides an insight into SQLite architecture,SQLite basics, and its Android connection. Chapter 2,Connecting the Dots,covers how to connect your database to Android views.It also covers some of the best practices one should follow in order to build a database-centric/database-enabled application. Chapter 3,Shiaring is Caring,will reflect on how to access and share data in Android via content providers and how to construct a content provider. Chapter 4,Thread Carefilly,will guide you on how to use loaders and ensure security of database and data.It will also provide you with tips to explore alternate approaches to building and using databases in Android applications. www.allitebooks.com
Preface Android is probably the buzzword of this decade. In a short span, it has taken over the majority of the handset market. Android is staged to take over wearables, our TV rooms, as well as our cars this autumn with the Android L release. With the frantic pace at which Android is growing, a developer needs to up his or her skill sets as well. Database-oriented application development is one of the key skills every developer should have. SQLite database in applications is the heart of a data-centric product and key to building great products. Understanding SQLite and implementing the Android database can be a steep learning curve for some people. Concepts such as content providers and loaders are more complex to understand and implement. Android SQLite Essentials equips developers with tools to build database-based Android applications in a simplistic manner. It is written keeping in mind the current needs and best practices being followed in the industry. Let us start our journey. What this book covers Chapter 1, Enter SQLite, provides an insight into SQLite architecture, SQLite basics, and its Android connection. Chapter 2, Connecting the Dots, covers how to connect your database to Android views. It also covers some of the best practices one should follow in order to build a database-centric/database-enabled application. Chapter 3, Sharing is Caring, will reflect on how to access and share data in Android via content providers and how to construct a content provider. Chapter 4, Thread Carefully, will guide you on how to use loaders and ensure security of database and data. It will also provide you with tips to explore alternate approaches to building and using databases in Android applications. www.allitebooks.com