Your SlideShare is downloading. ×
Android Programming                         Lecture 09                       Vladimir Kulyukin                Department o...
Resources   Source code and presentation materials for this lecture   are available at   http://vkedco.blogspot.com/2011/1...
Outline    ●      SQLite Database Adapters and Database      Helpers    ●      Universal Resource Identifiers and      Rep...
To Do List Project: DB Design and Implementation  ●      Design and implement a database adapter class to manage      data...
To Do List Project for Chapter 07           ToDoDBAdapter and toDoDBOpenHelperwww.youtube.com/vkedco            www.vkedco...
To Do List Project for Chapter 07                         ToDoListActwww.youtube.com/vkedco            www.vkedco.blogspot...
Uniform Resource Identifiers and              Representational State Transferswww.youtube.com/vkedco            www.vkedco...
Uniform Resource Identifier: URI   ●       A Uniform Resource Identifier (URI) is a string of       characters used to ide...
Representational State Transfer: REST   ●       REST is a style of software architecture for distributed       hypermedia ...
Content Providerswww.youtube.com/vkedco               www.vkedco.blogspot.com
What is a Content Provider?   ●       A Content Provider is a wrapper around data       source   ●       A SQLite database...
Saving and Retrieving Data through URIs    ●        Saving and retrieving data can be done only        through URIs    ●  ...
Data Encapsulation vs. Data Access    ●        It is conceptually easier to think of content        providers as data enca...
When to Use Content Providers    ●        Only if you need to share some data among        different applications    ●    ...
Androids Built-in Content Providers    ●        Several built-in providers are Browser, CallLog,        Contacts, MediaSto...
Content Providers as Web Siteswww.youtube.com/vkedco           www.vkedco.blogspot.com
Content Providers as Web Sites    ●        Each content provider registers itself on a device        as a web site    ●   ...
Authority Registration    ●        Authority must be registered in AndroidManifest.xml   <provider        android:name=".E...
Authority Registration   <provider        android:name=".EarthquakeProvider"        android:authorities="org.vkedco.provid...
Content URIswww.youtube.com/vkedco            www.vkedco.blogspot.com
Content URIs   ●       Data is retrieved from a content provider by       invoking a URI   ●       Retrieved data are a se...
Segments of a Content URI   ●     URI is content:// com.google.provider.NotePad   ●     content:// com.google.provider.Not...
Segments of a Content URI   ●       It is the content providers responsibility to       document and programmatically hand...
Content URIs   ●       Content providers provide REST-like URLs to       retrieve and manipulate data   ●       To identif...
Built-in Content URIs    ●      content://contacts/people/    ●      content://contacts/people/12    ●        These URIs d...
MIME Typeswww.youtube.com/vkedco           www.vkedco.blogspot.com
MIME Types   ●       A Web site returns a MIME type for a given URL   ●       A Browser starts a URL handling program depe...
MIME Types   ●       RFC document on the MIME standards is available at       http://tools.ietf.org/html/rfc2046   ●      ...
MIME Types  ●      Primary registered content types are application,      audio, example, image, message, model, multipart...
Non-Standard MIME Subtypes   ●       Subtypes that start with x- refer to non-standard types that       do not have to be ...
Non-Standard MIME Subtypes on Android   ●       For a single record, the Android MIME type is as follows:           – vnd....
Non-Standard MIME Subtypes on Android   ●       A Content provider must list which columns it supports   ●       There is ...
Non-Standard MIME Subtypes on Android   ●       A Content provider must list which columns it supports   ●       There is ...
Data Access with URIswww.youtube.com/vkedco             www.vkedco.blogspot.com
Reading Data with URIs   // 1. Define Uri for the collection   Uri peopleUri = Contacts.People.CONTENT_URI   // 2. Define ...
Retrieving Cursors from Content Providers     // 1. Create a project     String[] projection = new String[] {           Pe...
WHERE Clause    ●        Two ways of passing where clauses to a        content provider:           – Through URIs         ...
WHERE Clause Through URI     // Client-side query     String noteUri = “content://com.google.provider.NotePad/notes/12”;  ...
WHERE Clause Through String Arguments    // Client-side query    managedQuery(“content://com.google.provider.NotePad/notes...
Inserts, Updates, Deleteswww.youtube.com/vkedco             www.vkedco.blogspot.com
Inserting Records   ●       Android uses the class android.content.ContentValues to hold       values for a single record ...
Inserting Records  // 1. Use a ContentValues object to create a note  ContentValues note = new ContentValues();  note.put(...
Adding Files to Content Providers   ●       Sometimes you need to add a file to a database   ●       A common approach is ...
Adding Files to Content Providers     ContentValues bmp_record = new ContentValues();     bmp_record.put(“title”, “barcode...
Updates and Deletes      int numRowsUpdated =          activity.getContentResolver().update(Uri uri,                    Co...
Content Provider Implementationwww.youtube.com/vkedco         www.vkedco.blogspot.com
Implementing Content Providers  ●      Plan your database, URIs, column names, column types  ●      Extend the abstract cl...
Earthquake Content Provider  ●      We have created an application that allows us to view      earthquakes in a list view ...
EarthquakeViewer Content Provider                         Demowww.youtube.com/vkedco          www.vkedco.blogspot.com
Extentending ContentProvider and                Implementing Its Method                         EarthquakeProviderwww.yout...
Registering ContentProvider                         AndroidManifest.xmlwww.youtube.com/vkedco               www.vkedco.blo...
Using Content Provider                         EarthquakeViewerAct                    loadQuakesFromProvider(),           ...
References & Reading Suggestions    ●        http://developer.android.com/guide/topics/providers/content-providers.html   ...
Feedback      Bugs, errors to vladimir dot kulyukin at gmail      dot comwww.youtube.com/vkedco             www.vkedco.blo...
Android Programming: Lecture 09
Android Programming: Lecture 09
Upcoming SlideShare
Loading in...5
×

Android Programming: Lecture 09

3,924

Published on

1) SQLite Databases and SQLite Database Helpers
2) Universal Resource Identifiers and Representational State Transfer
3) Content Providers
4) Class home page is at http://vkedco.blogspot.com/2011/10/android-programming-lecture-09.html

Published in: Education, Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,924
On Slideshare
0
From Embeds
0
Number of Embeds
39
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Android Programming: Lecture 09"

  1. 1. Android Programming Lecture 09 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Resources Source code and presentation materials for this lecture are available at http://vkedco.blogspot.com/2011/10/android-programming-lecture-09.htmlwww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. Outline ● SQLite Database Adapters and Database Helpers ● Universal Resource Identifiers and Representational State Transfer ● Content Providerswww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. To Do List Project: DB Design and Implementation ● Design and implement a database adapter class to manage database transactions (ToDoDBAdapter) ● Inside the adapter class, design and implement a database helper class (toDoDBOpenHelper) to create tables and handles table upgrades ● The adapter class – publishes static database constants – handles queries and includes methods for creating, opening, and closing the database – provides strongly typed methods for adding remove and updating itemswww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. To Do List Project for Chapter 07 Demowww.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. To Do List Project for Chapter 07 ToDoDBAdapter and toDoDBOpenHelperwww.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. To Do List Project for Chapter 07 ToDoListActwww.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Uniform Resource Identifiers and Representational State Transferswww.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Uniform Resource Identifier: URI ● A Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource on the Internet ● URIs enable interaction representations of the resource over networks using specific protocols ● A URI is defined by its syntax and associated protocolswww.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Representational State Transfer: REST ● REST is a style of software architecture for distributed hypermedia systems such as WWW ● REST architecture consists of clients and servers ● Requests from clients and responses from servers are built around transfers of representations of resources ● A resource is any coherent and meaningful concept that may addressed ● A representation is a sequence of bits that captures the state of a resource ● Architectures that comply with REST standards are called RESTfulwww.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Content Providerswww.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. What is a Content Provider? ● A Content Provider is a wrapper around data source ● A SQLite database is an example of a data source that can be exposed as a content provider ● A Content Provider is a REST-like abstractionwww.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Saving and Retrieving Data through URIs ● Saving and retrieving data can be done only through URIs ● URIs are translated to underlying data access mechanisms ● Any application installed on the same device can use these URIs to manipulate the datawww.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Data Encapsulation vs. Data Access ● It is conceptually easier to think of content providers as data encapsulation mechanisms ● Why? Because content providers require an actual data access mechanism (database or network connection) on top of which they run ● The most frequent data access mechanism is the SQLite databasewww.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. When to Use Content Providers ● Only if you need to share some data among different applications ● For internal data access, you can use: – Preferences – Files – SQLite – Networkswww.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Androids Built-in Content Providers ● Several built-in providers are Browser, CallLog, Contacts, MediaStore, Settings ● These top-level providers are SQLite databases encapsulated as content providers ● Some of these databases have multiple tables: for example, Contacts has People, Phones, Photos, and Groups tables ● List of providers varies from Android OS to Android OSwww.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Content Providers as Web Siteswww.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Content Providers as Web Sites ● Each content provider registers itself on a device as a web site ● The registration is done with a string called authority ● Authority is similar to a domain name ● Authority string is the basis of a set of URIs the content provider offerswww.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Authority Registration ● Authority must be registered in AndroidManifest.xml <provider android:name=".EarthquakeProvider" android:authorities="org.vkedco.provider.earthquakeviewer"> </provider>www.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Authority Registration <provider android:name=".EarthquakeProvider" android:authorities="org.vkedco.provider.earthquakeviewer"> </provider> ● In the above registration, the provider serves the URLs with the prefix content://org.vkedco.provider.earthquakeviewerwww.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. Content URIswww.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. Content URIs ● Data is retrieved from a content provider by invoking a URI ● Retrieved data are a set of rows and columns in a Cursor object ● All content URIs have the same general form: – content://*/*/* – content:// com.google.provider.NotePad/notes/12www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. Segments of a Content URI ● URI is content:// com.google.provider.NotePad ● content:// com.google.provider.NotePad is the authority string used to locate the provider in the provider registry ● notes/12 is the path section specific to that provider ● notes and 12 are path segmentswww.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. Segments of a Content URI ● It is the content providers responsibility to document and programmatically handle paths and segments ● Convention: – 1) the first segment of the path points to a collection of objects (e.g., notes) – 2) the second segment of the path points to a specific object in that collection (e.g., 12)www.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. Content URIs ● Content providers provide REST-like URLs to retrieve and manipulate data ● To identify a directory or a collection of earthquakes ● URI content://org.vkedco.provider.earthquakeviewer/earthquakes identifies a directory/collection of earthquakes ● URI content://org.vkedco.provider.earthquakeviewer/earthquakes/2 identifies a specific earthquakewww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Built-in Content URIs ● content://contacts/people/ ● content://contacts/people/12 ● These URIs do not have fully qualified names because they are built-in ● All third-party content providers are recommended to have fully qualified pathswww.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. MIME Typeswww.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. MIME Types ● A Web site returns a MIME type for a given URL ● A Browser starts a URL handling program depending on the URLs MIME type ● MIME types work on Android in the same way they work in HTTP: a content provider can be asked for the MIME type of a given URI ● When asked about the MIME type, the provider returns a two-part string according to the standard web MIME conventionswww.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. MIME Types ● RFC document on the MIME standards is available at http://tools.ietf.org/html/rfc2046 ● A MIME type has two parts: a type and a subtype: – text/html – text/css – application/pdf ● Complete list of registered types and subtypes are at http://www.iana.org/assignments/media-typeswww.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. MIME Types ● Primary registered content types are application, audio, example, image, message, model, multipart, text, video ● Each primary type has subtypes ● If a vendor has proprietary data formats, the subtype name begins with vnd: application/vnd.ms- excel ● If it is a standard data format, the subtype does not start with any prefix: text/html or application/pdfwww.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Non-Standard MIME Subtypes ● Subtypes that start with x- refer to non-standard types that do not have to be registered ● These two types are typically defined bilaterally defined by collaborating applications/agents – application/x-tar – audio/x-aiff – video/x-msvideowww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Non-Standard MIME Subtypes on Android ● For a single record, the Android MIME type is as follows: – vnd.android.cursor.item/vnd.yourcompany.contenttype ● For a collection of records, the Android MIME type is as follows: – vnd.android.cursor.dir/vnd.yourcompany.contenttype ● Examples: – vnd.android.cursor.item/vnd.google.note – vnd.android.cursor.dir/vnd.google.notewww.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. Non-Standard MIME Subtypes on Android ● A Content provider must list which columns it supports ● There is no standard way of listing columns ● Typical methods of listing columns: – Constants and documentation – Interfaces and documentation ● Documentation or naming conventions should be used to indicate column types, because there is no formal way to indicate column typeswww.youtube.com/vkedco www.vkedco.blogspot.com
  34. 34. Non-Standard MIME Subtypes on Android ● A Content provider must list which columns it supports ● There is no standard way of listing columns ● Typical methods of listing columns: – Constants and documentation – Interfaces and documentation ● Documentation or naming conventions should be used to indicate column types, because there is no formal way to indicate column typeswww.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. Data Access with URIswww.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Reading Data with URIs // 1. Define Uri for the collection Uri peopleUri = Contacts.People.CONTENT_URI // 2. Define Uri for a record in the collection Uri personUri = peopleUri.withAppendedId(Contacts.People.CONTENT_URI, 12); // 3. Call Activitys managedQuery method with the record Uri to obtain a cursor Cursor c = managedQuery(personUri, null, null, null);www.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. Retrieving Cursors from Content Providers // 1. Create a project String[] projection = new String[] { People._ID, People.NAME, People.NUMBER }; // 2. Create a uri Uri contactsUri = Contacts.People.CONTENT_URI; // 3. Retrieve a cursor Cursor managedCursor = managedQuery(contactsUri, projection, // columns to return null, // no where clause Contacts.People.NAME + “ ASC”); // order bywww.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. WHERE Clause ● Two ways of passing where clauses to a content provider: – Through URIs – String clauses and string-array argumentswww.youtube.com/vkedco www.vkedco.blogspot.com
  39. 39. WHERE Clause Through URI // Client-side query String noteUri = “content://com.google.provider.NotePad/notes/12”; Cursor c = someActivity.managedQuery(noteUri, projection, // which columns to use null, // where clause null); // order by clause // Content providers side; uri is an incoming argument int note_id = uri.getPathSegments().get(1); // get 12 from the uriwww.youtube.com/vkedco www.vkedco.blogspot.com
  40. 40. WHERE Clause Through String Arguments // Client-side query managedQuery(“content://com.google.provider.NotePad/notes”, null, // no projection “_id=?”, // selection string clause new String[ ] { 12 }, // selection arguments null // no sort order ); // ? in selection clause are replaced with the corresponding strings // from the selection argumentswww.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. Inserts, Updates, Deleteswww.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. Inserting Records ● Android uses the class android.content.ContentValues to hold values for a single record to be inserted ● ContentValues is a dictionary of key/value pairs (essentially, column names and their values) ● To insert a record into a content provider: ● Populate a ContentValues object ● Use android.content.ContentResolver to insert ContentValues object into a content provider via a URIwww.youtube.com/vkedco www.vkedco.blogspot.com
  43. 43. Inserting Records // 1. Use a ContentValues object to create a note ContentValues note = new ContentValues(); note.put(“title”, “Teaching schedule”); note.put(“note”, “Android programming course 5:15 – 7:45pm”); // 2. Get a ContentResolver and insert a new note into the conect provider ContentResolver cr = activity.getContentResolver(); // Notepad.Notes.CONTENT_URI is the uri that corresponds in the // table and is published by the content provider Uri uri = cr.insert(Notepad.Notes.CONTENT_URI, note); // Returned uri has the following structure // Notepad.Notes.CONTENT_URI/new_note_idwww.youtube.com/vkedco www.vkedco.blogspot.com
  44. 44. Adding Files to Content Providers ● Sometimes you need to add a file to a database ● A common approach is 1) to save the file to disk and 2) insert/update a record in a database with the file path ● Android automates this approach by saving a reference to the file in a record with a reserved column name of “_data” ● Android returns a URI to the caller and the file must be saved at the location specified in the URIwww.youtube.com/vkedco www.vkedco.blogspot.com
  45. 45. Adding Files to Content Providers ContentValues bmp_record = new ContentValues(); bmp_record.put(“title”, “barcode 1023”); bmp_record.put(“annotation”, “blurry”); ContentResolver cr = activity.getContentResolver(); Uri uri = cr.insert(MyBitmapProvider.CONTENT_URI, bmp_record); Outputstream out = activity.getContentResolver().openOutputStream(uri) barcodeBitmap.compress(Bitmap.CompressFormat.JPEG, 50, out); out.close();www.youtube.com/vkedco www.vkedco.blogspot.com
  46. 46. Updates and Deletes int numRowsUpdated = activity.getContentResolver().update(Uri uri, ContentValues values, String whereClause, String[] selectionArgs); int numRowsDeleted = activity.getContentResolver().delete(Uri uri, ContentValues values, String whereClause, String[] selectionArgs);www.youtube.com/vkedco www.vkedco.blogspot.com
  47. 47. Content Provider Implementationwww.youtube.com/vkedco www.vkedco.blogspot.com
  48. 48. Implementing Content Providers ● Plan your database, URIs, column names, column types ● Extend the abstract class ContentProvider ● Implement the methods: – query – insert – update – Delete – getType ● Register the content provider in AndroidManifest.xmlwww.youtube.com/vkedco www.vkedco.blogspot.com
  49. 49. Earthquake Content Provider ● We have created an application that allows us to view earthquakes in a list view ● We can share this information with other applications ● Content Provider is an excellent mechanism for doing just that ● Principal Advantage: any application running on a specific Android device does not need to duplicate network traffic and XML parsingwww.youtube.com/vkedco www.vkedco.blogspot.com
  50. 50. EarthquakeViewer Content Provider Demowww.youtube.com/vkedco www.vkedco.blogspot.com
  51. 51. Planning Database Column Names _id date details latitude longitude magnitude link Column Numbers 0 1 2 3 4 5 6www.youtube.com/vkedco www.vkedco.blogspot.com
  52. 52. Extentending ContentProvider and Implementing Its Method EarthquakeProviderwww.youtube.com/vkedco www.vkedco.blogspot.com
  53. 53. Registering ContentProvider AndroidManifest.xmlwww.youtube.com/vkedco www.vkedco.blogspot.com
  54. 54. Using Content Provider EarthquakeViewerAct loadQuakesFromProvider(), addNewDBQuake()www.youtube.com/vkedco www.vkedco.blogspot.com
  55. 55. References & Reading Suggestions ● http://developer.android.com/guide/topics/providers/content-providers.html ● Chapters 6, 7 in “Professional Android 2 Application Development” by Rito Meier ● Chapter 3 in “Pro Android 2” by Hashimi, Komatineni, MacLean ● http://en.wikipedia.org/wiki/Uniform_Resource_Identifierwww.youtube.com/vkedco www.vkedco.blogspot.com
  56. 56. Feedback Bugs, errors to vladimir dot kulyukin at gmail dot comwww.youtube.com/vkedco www.vkedco.blogspot.com

×