SlideShare a Scribd company logo
1 of 74
Download to read offline
Douglas C. Schmidt
d.schmidt@vanderbilt.edu
www.dre.vanderbilt.edu/~schmidt
Professor of Computer Science
Institute for Software
Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA
Android Persistent Data Storage:
Introduction
Android Persistent Data Storage Douglas C. Schmidt
2
Data Storage Options on Android
• Android offers several ways to store
data
• SQLite database
• Files
• SharedPreferences
Douglas C. Schmidt
d.schmidt@vanderbilt.edu
www.dre.vanderbilt.edu/~schmidt
Professor of Computer Science
Institute for Software
Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA
Android Persistent Data Storage:
Overview of SQLite
Android Persistent Data Storage Douglas C. Schmidt
4
Learning Objectives in this Part of the Module
• Understand what SQLite is & how to use it in Android
Android Persistent Data Storage Douglas C. Schmidt
5
Android SQLite
• Android supports SQLite, which provides
a relational database for a mobile device
• i.e., it contains tables (consisting of
rows & columns), indexes, etc. that
form a “schema”
www.drdobbs.com/database/using-sqlite-on-android/232900584
Android Persistent Data Storage Douglas C. Schmidt
6
Android SQLite
• Android supports SQLite, which provides
a relational database for a mobile device
• It’s designed to operate within a
small footprint (~350kB) within
a single cross-platform disk file
en.wikipedia.org/wiki/SQLite
Android Persistent Data Storage Douglas C. Schmidt
7
Android SQLite
• Android supports SQLite, which provides
a relational database for a mobile device
• It’s designed to operate within a
small footprint (<300kB) within
a single cross-platform disk file
• Implements most of SQL92 &
supports so-called “ACID”
transactions
• Atomic, Consistent, Isolated, & Durable
en.wikipedia.org/wiki/SQL-92
Android Persistent Data Storage Douglas C. Schmidt
8
Android SQLite
• Android supports SQLite, which provides
a relational database for a mobile device
• It’s designed to operate within a
small footprint (<300kB) within
a single cross-platform disk file
• Implements most of SQL92 &
supports so-called “ACID”
transactions
• Access to an SQLite database typically
involves accessing the Android filesystem
• Database operations are typically
asynchronous since filesystem access
can be slow
• e.g., access is often made via AsyncTask,
AsyncQueryHandler, CursorLoader, etc.
www.vogella.com/articles/AndroidSQLite/article.html
Android Persistent Data Storage Douglas C. Schmidt
9
SQLiteDatabase
• SQLiteDatabase is the base class
for working with a SQLite database
in Android
• It provides the insert(),
update(), & delete() methods
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Android Persistent Data Storage Douglas C. Schmidt
10
SQLiteDatabase
• SQLiteDatabase is the base class
for working with a SQLite database
in Android
• It provides the insert(),
update(), & delete() methods
• It also provides the execSQL()
method that can execute an
SQL statement directly
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Android Persistent Data Storage Douglas C. Schmidt
11
SQLiteDatabase
• SQLiteDatabase is the base class
for working with a SQLite database
in Android
• Queries can be created via
rawQuery() & query() methods or
via the SQLiteQueryBuilder class
developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html
Android Persistent Data Storage Douglas C. Schmidt
12
ContentValues
developer.android.com/reference/android/content/ContentValues.html
• The ContentValues object is used
by SQLiteDatabase to define
key/values
• The “key” represents the table
column identifier & the “value”
represents the content for the
table record in this column
Android Persistent Data Storage Douglas C. Schmidt
13
ContentValues
developer.android.com/reference/android/content/ContentValues.html
• The ContentValues object is used
by SQLiteDatabase to define
key/values
• ContentValues can be used for
inserts & updates of database
entries
Android Persistent Data Storage Douglas C. Schmidt
14
SQLiteOpenHelper
• Recommended means of using
SQLiteDatabase is to subclass the
SQLiteOpenHelper class
• In constructor call the super()
method of SQLiteOpenHelper,
specifying database name &
current database version
developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Android Persistent Data Storage Douglas C. Schmidt
15
SQLiteOpenHelper
• Recommended means of using
SQLiteDatabase is to subclass the
SQLiteOpenHelper class
• In constructor call the super()
method of SQLiteOpenHelper,
specifying database name &
current database version
• Override onCreate(), which is
called by SQLite if the database
does not yet exist
• e.g., execute CREATE TABLE
command
developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Android Persistent Data Storage Douglas C. Schmidt
16
SQLiteOpenHelper
• Recommended means of using
SQLiteDatabase is to subclass the
SQLiteOpenHelper class
• In constructor call the super()
method of SQLiteOpenHelper,
specifying database name &
current database version
• Override onCreate(), which is
called by SQLite if the database
does not yet exist
• Override onUpgrade(), which is
called if the database version
increases in App code to allow
database schema updates
developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Android Persistent Data Storage Douglas C. Schmidt
17
SQLiteOpenHelper
• Recommended means of using
SQLiteDatabase is to subclass the
SQLiteOpenHelper class
• Use SQLiteOpenHelper methods to
open & return underlying database
• e.g., getReadableDatabase() &
getWriteableDatabase() to
access an SQLiteDatabase
object either in read or write
mode, respectively
developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Android Persistent Data Storage Douglas C. Schmidt
18
Opening an SQLite Database
public class ArtistDatabaseHelper extends SQLiteOpenHelper {
final private static String CREATE_CMD =
"CREATE TABLE artists ("
+ "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name" + " TEXT NOT NULL)";
public ArtistDatabaseHelper(Context context) {
super(context, "artists_db", null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CMD);
}
public void onUpgrade(SQLiteDatabase db,
int oldVersion, int newVersion) { /* ... */ }
...
It’s common to create an SQLiteOpenHelper subclass for each SQL table
Create the SQL table
SQL commands to create a table of artists
Give a name to the table
Support schema evolution
Android Persistent Data Storage Douglas C. Schmidt
19
Using an SQLite Database Via an Activity
public class DatabaseExampleActivity extends ListActivity {
final static String[] columns ={"_id", "name"};
static SQLiteDatabase db = null;
public void onCreate(Bundle savedInstanceState) {
...
ArtistDatabaseHelper dbHelper =
new ArtistDatabaseHelper
(getActivity().getApplicationContext());
db = dbHelper.getWritableDatabase();
insertArtists();
deleteLadyGaga();
Cursor c = readArtists();
displayArtists(c);
}
...
SQLiteDatabase is often put in an App singleton to simplify access
Make the SQLiteOpenHelper subclass instance
Create a read/write databse
Perform various operations
Android Persistent Data Storage Douglas C. Schmidt
20
Inserting Values Into an SQLite Database
• Method for inserting a row into the database
public long insert (String table, String nullColHack, ContentValues values)
Parameters
table The table to insert the row into
nullColHack Optional (often null)
values Map containing initial col values for row; keys are col names
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#insert(java.lang.String, java.lang.String, android.content.ContentValues)
Android Persistent Data Storage Douglas C. Schmidt
21
Inserting Values Into an SQLite Database
• Method for inserting a row into the database
public long insert (String table, String nullColHack, ContentValues values)
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#insert(java.lang.String, java.lang.String, android.content.ContentValues)
Android Persistent Data Storage Douglas C. Schmidt
22
Inserting Values Into an SQLite Database
private void insertArtists() {
ContentValues values = new ContentValues();
values.put("name", "Lady Gaga");
db.insert("artists", null, values);
values.clear();
values.put("name", "Johnny Cash");
db.insert("artists", null, values);
values.clear();
values.put("name", "Sting");
db.insert("artists", null, values);
...
}
“key” represents the table column identifier & the “value”
represents the content for the table record in this column
Android Persistent Data Storage Douglas C. Schmidt
23
Deleting a Row From an SQLite Database
Parameters
table the table to delete from
whereClause optional WHERE clause to apply when deleting
whereArgs Passing null deletes all rows
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#delete(java.lang.String, java.lang.String, java.lang.String[])
• Method for deleting row(s) from the database
public int delete(String table, String whereClause, String[] whereArgs)
Android Persistent Data Storage Douglas C. Schmidt
24
Deleting a Row From an SQLite Database
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#delete(java.lang.String, java.lang.String, java.lang.String[])
• Method for deleting row(s) from the database
public int delete(String table, String whereClause, String[] whereArgs)
Android Persistent Data Storage Douglas C. Schmidt
25
Deleting a Row From an SQLite Database
private int deleteLadyGaga() {
return db.delete("artists",
"name" + "=?",
new String []
{"Lady Gaga"});
}
Remove Lady Gaga from the database of artists
Note the use of
the “whereArgs”
Android Persistent Data Storage Douglas C. Schmidt
26
Querying an SQLite Database
• You can use rawQuery() or a query() on an SQLiteDatabase
public Cursor rawQuery(String sql, String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set
Parameters
Returns
A Cursor object, which is positioned before the first entry
sql the SQL query. The SQL string must not be ; terminated
selectionArgs You may include ?’s in where clause in the query, which are
replaced by the values from selectionArgs (the values will be
bound as Strings)
Cursors aren’t synchronized, see documentation for details
Android Persistent Data Storage Douglas C. Schmidt
27
Querying an SQLite Database
• You can use rawQuery() or a query() on an SQLiteDatabase
public Cursor query(String table, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy)
query() builds up a SQL SELECT statement from its component parts
Parameter
String table The table name to compile the query against
int[] columns A list of which table columns to return ("null" returns all columns)
String selection Where-clause filters for the selection of data (null selects all data)
String[]
selectionArgs
You may include ?s in the “selection” where-clause that get replaced
by the values from the selectionArgs array
String[] groupBy A filter declaring how to group rows (null means rows not grouped)
String[] having Filter for the groups (null means no filter)
String[] orderBy Table columns used to order the data (null means no ordering)
Returns
A Cursor object, which is positioned before the first entry
Android Persistent Data Storage Douglas C. Schmidt
28
Using Query() vs. rawQuery()
private Cursor readArtists() {
// returns all rows
return db.rawQuery("SELECT _id, name FROM artists", null);
}
• Using rawQuery() on an SQLiteDatabase
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#rawQuery(java.lang.String, java.lang.String[])
Android Persistent Data Storage Douglas C. Schmidt
29
Using Query() vs. rawQuery()
private Cursor readArtists() {
// returns all rows
return db.query("artists", new String [] {"_id", "name"},
null, null, null, null, null);
}
private Cursor readArtists() {
// returns all rows
return db.rawQuery("SELECT _id, name FROM artists", null);
}
• Using rawQuery() on an SQLiteDatabase
• Using query() on an SQLiteDatabase
developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
#query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[],
java.lang.String, java.lang.String, java.lang.String)
Android Persistent Data Storage Douglas C. Schmidt
30
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• This allows buffering of query
results efficiently since all data
needn’t be loaded into memory
Android Persistent Data Storage Douglas C. Schmidt
31
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
Android Persistent Data Storage Douglas C. Schmidt
32
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
• moveToFirst() & moveToNext()
move between individual data rows
Android Persistent Data Storage Douglas C. Schmidt
33
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
• moveToFirst() & moveToNext()
move between individual data rows
• isAfterLast() checks if the end of
the query result has been reached
Android Persistent Data Storage Douglas C. Schmidt
34
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
• moveToFirst() & moveToNext()
move between individual data rows
• isAfterLast() checks if the end of
the query result has been reached
• Provides typed get*() methods
• e.g., getLong(columnIndex) &
getString(columnIndex) to access
column data for current position
of result
Android Persistent Data Storage Douglas C. Schmidt
35
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
• moveToFirst() & moveToNext()
move between individual data rows
• isAfterLast() checks if the end of
the query result has been reached
• Provides typed get*() methods
• Provides getColumnIndexOrThrow
(String) to get column index for a
column name of table
Android Persistent Data Storage Douglas C. Schmidt
36
Cursor Iterators
developer.android.com/reference/android/database/Cursor.html
• Query() returns a Cursor Iterator
that represents result of a query &
points to one row of query result
• getCount() returns # of elements
of the resulting query
• moveToFirst() & moveToNext()
move between individual data rows
• isAfterLast() checks if the end of
the query result has been reached
• Provides typed get*() methods
• Provides getColumnIndexOrThrow
(String) to get column index for a
column name of table
• Must be closed via close()
Android Persistent Data Storage Douglas C. Schmidt
37
Displaying an SQLite Database
private void displayArtists (Cursor c) {
setListAdapter(
new SimpleCursorAdapter
(this, R.layout.list_layout, c,
new String [] {"_id", "name"},
new int[] { R.id._id, R.id.name }));
}
developer.android.com/reference/android/widget/SimpleCursorAdapter.html
• The SimpleCursorAdapter class maps the
columns to the Views based on
the Cursor passed to it
Android Persistent Data Storage Douglas C. Schmidt
38
Examining an SQLite Database
• If your App creates a database it is saved by default in a directory file
/DATA/data/APP_NAME/databases/FILENAME
• DATA is the path that the Environment. getDataDirectory() method returns
• APP_NAME is your app name
• FILENAME is the name you specify in your application code for the
database
Android Persistent Data Storage Douglas C. Schmidt
39
Examining an SQLite Database
• If your App creates a database it is saved by default in a directory file
• You can examine this database with sqlite3
# adb shell
# sqlite3 /data/data/com.android.launcher/databases/launcher.db
Android Persistent Data Storage Douglas C. Schmidt
40
Summary
• SQLite is embedded into every Android device
• Using an SQLite database in Android does not require a setup procedure or
administration of the database
Android Persistent Data Storage Douglas C. Schmidt
41
Summary
• SQLite is embedded into every Android device
• You only have to define the SQL statements for creating & updating the
database
• Afterwards the database is automatically managed for you by the Android
platform
Douglas C. Schmidt
d.schmidt@vanderbilt.edu
www.dre.vanderbilt.edu/~schmidt
Professor of Computer Science
Institute for Software
Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA
Android Content Providers:
Introduction
Developing Android Apps with Eclipse Douglas C. Schmidt
43
Overview of Content Providers
• ContentProviders manage access to a central
repository of structured data & can make an
App’s data available to other Apps
developer.android.com/guide/topics/providers/content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
44
Overview of Content Providers
• ContentProviders manage access to a central
repository of structured data & can make an
App’s data available to other Apps
• They encapsulate the data & provide
mechanisms for defining data security
developer.android.com/guide/topics/providers/content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
45
Overview of Content Providers
• ContentProviders manage access to a central
repository of structured data & can make an
App’s data available to other Apps
• They encapsulate the data & provide
mechanisms for defining data security
• Content providers are the standard interface
that connects data in one process with code
running in another process
developer.android.com/guide/topics/providers/content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
46
Overview of Content Providers
• ContentProviders manage access to a central
repository of structured data & can make an
App’s data available to other Apps
• They encapsulate the data & provide
mechanisms for defining data security
• Content providers are the standard interface
that connects data in one process with code
running in another process
• Content providers support database “CRUD”
operations (Create, Read, Update, Delete),
where “read” is implemented as “query”
developer.android.com/guide/topics/providers/content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
47
Overview of Content Providers
• ContentProviders manage access to a central
repository of structured data & can make an
App’s data available to other Apps
• They encapsulate the data & provide
mechanisms for defining data security
• Content providers are the standard interface
that connects data in one process with code
running in another process
• Content providers support database “CRUD”
operations (Create, Read, Update, Delete),
where “read” is implemented as “query”
• Apps can provide Activities that allow
users to query & modify the data managed
by a provider
developer.android.com/guide/topics/providers/content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
48
Example Android ContentProviders
• Android itself includes many Content
Providers that manage data for
• Browser – bookmarks, history
• Call log – telephone usage
• Contacts – contact data
• MMS/SMS – Stores messages sent
& received
• Media – media database
• UserDictionary – database for
predictive spelling
• Maps – previous searches
• YouTube – previous searches
• Many more
developer.android.com/reference/android/provider/package-summary.html
Developing Android Apps with Eclipse Douglas C. Schmidt
49
ContentProvider Data Model
• A content provider typically
presents data to external
Apps as one or more tables
• e.g., the tables found in
a relational SQL
database
Developing Android Apps with Eclipse Douglas C. Schmidt
50
ContentProvider Data Model
• A content provider typically
presents data to external
Apps as one or more tables
• A row represents an
instance of some type of
data the provider collects
• Each column in a row
represents an individual
piece of data collected
for an instance
word app id freq locale _ID
mapreduce user1 100 en_US 1
precompiler user14 200 fr_FR 2
applet user2 225 fr_CA 3
const user1 255 pt_BR 4
int user5 100 en_UK 5
One provider in Android is the
user dictionary, which stores the
spellings of non-standard words
that the user wants to keep
Developing Android Apps with Eclipse Douglas C. Schmidt
51
Overview of ContentResolver
• ContentProvider never accessed
directly, but accessed indirectly
via a ContentResolver
• ContentProvider not created
until a ContentResolver tries
to access it
developer.android.com/reference/android/content/ContentResolver.html
Developing Android Apps with Eclipse Douglas C. Schmidt
52
Overview of ContentResolver
• ContentProvider never accessed
directly, but accessed indirectly
via a ContentResolver
• ContentResolvers manage &
support ContentProviders
• Enables use of ContentProviders
across multiple Apps
developer.android.com/reference/android/content/ContentResolver.html
Developing Android Apps with Eclipse Douglas C. Schmidt
53
Overview of ContentResolver
• ContentProvider never accessed
directly, but accessed indirectly
via a ContentResolver
• ContentResolvers manage &
support ContentProviders
• Enables use of ContentProviders
across multiple Apps
• Provides additional services, such
as change notification & IPC
developer.android.com/reference/android/content/ContentResolver.html
Developing Android Apps with Eclipse Douglas C. Schmidt
54
Overview of ContentResolver
• ContentProvider never accessed
directly, but accessed indirectly
via a ContentResolver
• ContentResolvers manage &
support ContentProviders
• Context.getContentResolver()
accesses default ContentResolver
ContentResolver cr =
getContentResolver();
developer.android.com/reference/android/content/ContentResolver.html
Developing Android Apps with Eclipse Douglas C. Schmidt
55
• When you query data via a
ContentProvider, you don't
communicate with the provider
directly
• Instead, you use a
ContentResolver object to
communicate with the provider
ContentResolver vs. ContentProvider
www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
56
ContentResolver vs. ContentProvider
• When you query data via a
ContentProvider, you don't
communicate with the provider
directly
• A call to getContentResolver().
query() is made
• This method call invokes
ContentResolver.query(), not
ContentProvider.query()
www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
57
ContentResolver vs. ContentProvider
• When you query data via a
ContentProvider, you don't
communicate with the provider
directly
• A call to getContentResolver().
query() is made
• When this query method is
invoked, the Content Resolver
parses the uri argument & extracts
its authority
• The Content Resolver directs the
request to the content provider
registered with the (unique)
authority by calling the Content
Provider's query() method
www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
58
ContentResolver vs. ContentProvider
• When you query data via a
ContentProvider, you don't
communicate with the provider
directly
• A call to getContentResolver().
query() is made
• When this query method is invoked,
the Content Resolver parses the uri
argument & extracts its authority
• When the Content Provider's query()
method is invoked, the query is
performed & a Cursor is returned (or
an exception is thrown)
• The resulting behavior depends on
Content Provider's implementation
www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
Developing Android Apps with Eclipse Douglas C. Schmidt
59
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
Developing Android Apps with Eclipse Douglas C. Schmidt
60
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
• e.g., content://authority/path/id
• content - data is managed by a
ContentProvider
Developing Android Apps with Eclipse Douglas C. Schmidt
61
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
• e.g., content://authority/path/id
• content - data is managed by a
ContentProvider
• authority – id for the content provider
Developing Android Apps with Eclipse Douglas C. Schmidt
62
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
• e.g., content://authority/path/id
• content - data is managed by a
ContentProvider
• authority – id for the content provider
• path – 0 or more segments indicating
the type of data to access
Developing Android Apps with Eclipse Douglas C. Schmidt
63
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
• e.g., content://authority/path/id
• content - data is managed by a
ContentProvider
• authority – id for the content provider
• path – 0 or more segments indicating
the type of data to access
• id – specific record being requested
Developing Android Apps with Eclipse Douglas C. Schmidt
64
Content URIs
• Any URI that begins with the content://
scheme represents a resource served up
by a Content Provider
• e.g., content://authority/path/id
• ContentProviders are a façade that
offers data encapsulation via Content
Uri objects used as handles
• The data could be stored in a SQLite
database, in flat files, retrieved off a
device, be stored on some server
accessed over the Internet, etc.
Developing Android Apps with Eclipse Douglas C. Schmidt
65
Inserting Data Via ContentResolver
• Use ContentResolver.insert() to insert data into a ContentProvider
public final Uri insert(Uri uri, ContentValues values)
• Inserts a row into a table at the given URI
• If the content provider supports transactions the insertion will be atomic
Parameters
• uri – The uri of the table to insert into
• values – The initial values for the newly inserted row, where the key is
the column name for the field (passing an empty ContentValues will
create an empty row)
Returns
• the URI of the newly created row
developer.android.com/reference/android/content/ContentProvider.html
#insert(android.net.Uri, android.content.ContentValues)
Developing Android Apps with Eclipse Douglas C. Schmidt
66
Deleting Data Via ContentResolver
• Use ContentResolver.delete() to delete data from a ContentProvider
public final int delete(Uri uri, String where, String[] selectionArgs)
• Deletes row(s) specified by a content URI. If the content provider
supports transactions, the deletion will be atomic
Parameters
• uri – The uri of the row to delete
• where – A filter to apply to rows before deleting, formatted as an SQL
WHERE clause (excluding the WHERE itself)
• selectionArgs – SQL pattern args
Returns
• The number of rows deleted
developer.android.com/reference/android/content/ContentProvider.html
#delete(android.net.Uri, java.lang.String, java.lang.String[])
Developing Android Apps with Eclipse Douglas C. Schmidt
67
Inserting/Deleting via applyBatch()
• ContentResolver.applyBatch() can insert (& delete) groups of data
public ContentProviderResult[] applyBatch (String authority,
ArrayList<ContentProviderOperation> operations)
• Applies each ContentProviderOperation object & returns array of results
• If all the applications succeed then a ContentProviderResult array with the
same number of elements as the operations will be returned
Parameters
• authority –authority of the ContentProvider to apply this batch
• operations – the operations to apply
Returns
• the results of the applications
developer.android.com/reference/android/content/ContentProvider.html
#applyBatch(java.util.ArrayList<android.content.ContentProviderOperation>)
Developing Android Apps with Eclipse Douglas C. Schmidt
68
Querying a ContentResolver
• Use ContentResolver. query()
to retrieve data
• Returns a Cursor instance
for accessing results
• A Cursor is an iterator over
a result set
developer.android.com/reference/android/content/ContentProvider.html#query
(Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
Developing Android Apps with Eclipse Douglas C. Schmidt
69
query() Parameters Compared to SQL Query
query()
argument
SELECT
keyword/parameter
Notes
Uri FROM table_name Uri maps to the table in the provider
named table_name
projection col,col,col,... projection is an array of columns that
should be included for each row
retrieved
selection WHERE col =value selection specifies the criteria for
selecting rows
selectionArgs No exact equivalent in
SQL
Selection arguments replace the ?
placeholders in the selection clause
sortOrder ORDER BYcol,col,... sortOrder specifies the order in which
rows appear in the returned Cursor
Developing Android Apps with Eclipse Douglas C. Schmidt
70
Summary
• A SQLite database is private to the
App which creates it
• If you want to share data with other
App you can use a content provider
Developing Android Apps with Eclipse Douglas C. Schmidt
71
Summary
• A SQLite database is private to the
App which creates it
• A content provider allows App to
access data
• In most cases this data is stored
in an SQlite database
Developing Android Apps with Eclipse Douglas C. Schmidt
72
Summary
• A SQLite database is private to the
App which creates it
• A content provider allows App to
access data
• While a content provider can be used
within an App to access data, its is
typically used to share data with other
App
Developing Android Apps with Eclipse Douglas C. Schmidt
73
Summary
• A SQLite database is private to the
App which creates it
• A content provider allows App to
access data
• While a content provider can be used
within an App to access data, its is
typically used to share data with other
App
• App data is by default private, so a
content provider is a convenient to
share you data with other application
based on a structured interface
Developing Android Apps with Eclipse Douglas C. Schmidt
74
Summary
• A SQLite database is private to the
App which creates it
• A content provider allows App to
access data
• While a content provider can be used
within an App to access data, its is
typically used to share data with other
App
• App data is by default private, so a
content provider is a convenient to
share you data with other application
based on a structured interface
• A content provider must be declared
in the AndroidManifest.xml file

More Related Content

What's hot

Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
android sqlite
android sqliteandroid sqlite
android sqliteDeepa Rani
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data StorageMingHo Chang
 

What's hot (12)

Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
android sqlite
android sqliteandroid sqlite
android sqlite
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
 

Viewers also liked

Visual studio-2012-product-guide
Visual studio-2012-product-guideVisual studio-2012-product-guide
Visual studio-2012-product-guideAravindharamanan S
 
Introducing visual studio_2010_v1.0--chappell
Introducing visual studio_2010_v1.0--chappellIntroducing visual studio_2010_v1.0--chappell
Introducing visual studio_2010_v1.0--chappellAravindharamanan S
 
Rad grid dynamically building a grid and adding a hierarchy with declarative...
Rad grid  dynamically building a grid and adding a hierarchy with declarative...Rad grid  dynamically building a grid and adding a hierarchy with declarative...
Rad grid dynamically building a grid and adding a hierarchy with declarative...Aravindharamanan S
 
Workshop 04 android-development
Workshop 04 android-developmentWorkshop 04 android-development
Workshop 04 android-developmentAravindharamanan S
 
Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Aravindharamanan S
 
Emergency androidstudiochapter
Emergency androidstudiochapterEmergency androidstudiochapter
Emergency androidstudiochapterAravindharamanan S
 
Twdatasci cjlin-big data analytics - challenges and opportunities
Twdatasci cjlin-big data analytics - challenges and opportunitiesTwdatasci cjlin-big data analytics - challenges and opportunities
Twdatasci cjlin-big data analytics - challenges and opportunitiesAravindharamanan S
 

Viewers also liked (19)

Robust recommendation
Robust recommendationRobust recommendation
Robust recommendation
 
Visual studio-2012-product-guide
Visual studio-2012-product-guideVisual studio-2012-product-guide
Visual studio-2012-product-guide
 
Lecture 3 soap
Lecture 3 soapLecture 3 soap
Lecture 3 soap
 
Android wear notes
Android wear notesAndroid wear notes
Android wear notes
 
Introducing visual studio_2010_v1.0--chappell
Introducing visual studio_2010_v1.0--chappellIntroducing visual studio_2010_v1.0--chappell
Introducing visual studio_2010_v1.0--chappell
 
Rad grid dynamically building a grid and adding a hierarchy with declarative...
Rad grid  dynamically building a grid and adding a hierarchy with declarative...Rad grid  dynamically building a grid and adding a hierarchy with declarative...
Rad grid dynamically building a grid and adding a hierarchy with declarative...
 
Workshop 04 android-development
Workshop 04 android-developmentWorkshop 04 android-development
Workshop 04 android-development
 
Aws tkv-ug
Aws tkv-ugAws tkv-ug
Aws tkv-ug
 
Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0
 
Release documentation
Release documentationRelease documentation
Release documentation
 
Collab filtering-tutorial
Collab filtering-tutorialCollab filtering-tutorial
Collab filtering-tutorial
 
Recommender lecture
Recommender lectureRecommender lecture
Recommender lecture
 
Emergency androidstudiochapter
Emergency androidstudiochapterEmergency androidstudiochapter
Emergency androidstudiochapter
 
Collaborative filtering
Collaborative filteringCollaborative filtering
Collaborative filtering
 
Lec7 collaborative filtering
Lec7 collaborative filteringLec7 collaborative filtering
Lec7 collaborative filtering
 
Wcf tutorial
Wcf tutorialWcf tutorial
Wcf tutorial
 
Item based approach
Item based approachItem based approach
Item based approach
 
Brian.suda.thesis
Brian.suda.thesisBrian.suda.thesis
Brian.suda.thesis
 
Twdatasci cjlin-big data analytics - challenges and opportunities
Twdatasci cjlin-big data analytics - challenges and opportunitiesTwdatasci cjlin-big data analytics - challenges and opportunities
Twdatasci cjlin-big data analytics - challenges and opportunities
 

Similar to 9 content-providers

Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Khaled Anaqwa
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptxFaezNasir
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for AndroidJakir Hossain
 
Sqlite
SqliteSqlite
SqliteKumar
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 
Rajab Davudov - Android Database
Rajab Davudov - Android DatabaseRajab Davudov - Android Database
Rajab Davudov - Android DatabaseRashad Aliyev
 
StORM: a lightweight ORM for Android SQLite
StORM: a lightweight ORM for Android SQLiteStORM: a lightweight ORM for Android SQLite
StORM: a lightweight ORM for Android SQLiteDavid Chandler
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.pptCNSHacking
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.pptLokeshK66
 

Similar to 9 content-providers (20)

Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Fastest offline with SQLite
Fastest offline with SQLiteFastest offline with SQLite
Fastest offline with SQLite
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Sqlite
SqliteSqlite
Sqlite
 
GAAD Database presentation
GAAD Database presentationGAAD Database presentation
GAAD Database presentation
 
F1
F1F1
F1
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
Rajab Davudov - Android Database
Rajab Davudov - Android DatabaseRajab Davudov - Android Database
Rajab Davudov - Android Database
 
StORM: a lightweight ORM for Android SQLite
StORM: a lightweight ORM for Android SQLiteStORM: a lightweight ORM for Android SQLite
StORM: a lightweight ORM for Android SQLite
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Sql security
Sql securitySql security
Sql security
 
Sql Portfolio
Sql PortfolioSql Portfolio
Sql Portfolio
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.ppt
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.ppt
 
Modern android development
Modern android developmentModern android development
Modern android development
 

Recently uploaded

原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档208367051
 
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`dajasot375
 
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degreeyuu sss
 
Cosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable BricksCosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable Bricksabhishekparmar618
 
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一z xss
 
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一F dds
 
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一diploma 1
 
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degreeyuu sss
 
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...Amil baba
 
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一Fi L
 
Design Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryDesign Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryWilliamVickery6
 
PORTAFOLIO 2024_ ANASTASIYA KUDINOVA
PORTAFOLIO   2024_  ANASTASIYA  KUDINOVAPORTAFOLIO   2024_  ANASTASIYA  KUDINOVA
PORTAFOLIO 2024_ ANASTASIYA KUDINOVAAnastasiya Kudinova
 
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
Architecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfArchitecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfSumit Lathwal
 
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Service
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts ServiceCall Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Service
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Servicejennyeacort
 
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full NightCall Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
How to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our SiteHow to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our Sitegalleryaagency
 
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改yuu sss
 
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一lvtagr7
 

Recently uploaded (20)

原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
 
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
Abu Dhabi Call Girls O58993O4O2 Call Girls in Abu Dhabi`
 
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国亚利桑那大学毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
 
Cosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable BricksCosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable Bricks
 
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一
办理(UC毕业证书)查尔斯顿大学毕业证成绩单原版一比一
 
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一
办理学位证(SFU证书)西蒙菲莎大学毕业证成绩单原版一比一
 
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一
办理(USYD毕业证书)澳洲悉尼大学毕业证成绩单原版一比一
 
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
原版美国亚利桑那州立大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
 
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一
办理学位证(NUS证书)新加坡国立大学毕业证成绩单原版一比一
 
Design Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William VickeryDesign Portfolio - 2024 - William Vickery
Design Portfolio - 2024 - William Vickery
 
PORTAFOLIO 2024_ ANASTASIYA KUDINOVA
PORTAFOLIO   2024_  ANASTASIYA  KUDINOVAPORTAFOLIO   2024_  ANASTASIYA  KUDINOVA
PORTAFOLIO 2024_ ANASTASIYA KUDINOVA
 
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
Call Girls In Safdarjung Enclave 24/7✡️9711147426✡️ Escorts Service
 
Architecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfArchitecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdf
 
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Service
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts ServiceCall Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Service
Call Girls in Ashok Nagar Delhi ✡️9711147426✡️ Escorts Service
 
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full NightCall Girls Satellite 7397865700 Ridhima Hire Me Full Night
Call Girls Satellite 7397865700 Ridhima Hire Me Full Night
 
How to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our SiteHow to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our Site
 
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改
1比1办理美国北卡罗莱纳州立大学毕业证成绩单pdf电子版制作修改
 
Call Girls in Pratap Nagar, 9953056974 Escort Service
Call Girls in Pratap Nagar,  9953056974 Escort ServiceCall Girls in Pratap Nagar,  9953056974 Escort Service
Call Girls in Pratap Nagar, 9953056974 Escort Service
 
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
定制(RMIT毕业证书)澳洲墨尔本皇家理工大学毕业证成绩单原版一比一
 

9 content-providers

  • 1. Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Android Persistent Data Storage: Introduction
  • 2. Android Persistent Data Storage Douglas C. Schmidt 2 Data Storage Options on Android • Android offers several ways to store data • SQLite database • Files • SharedPreferences
  • 3. Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Android Persistent Data Storage: Overview of SQLite
  • 4. Android Persistent Data Storage Douglas C. Schmidt 4 Learning Objectives in this Part of the Module • Understand what SQLite is & how to use it in Android
  • 5. Android Persistent Data Storage Douglas C. Schmidt 5 Android SQLite • Android supports SQLite, which provides a relational database for a mobile device • i.e., it contains tables (consisting of rows & columns), indexes, etc. that form a “schema” www.drdobbs.com/database/using-sqlite-on-android/232900584
  • 6. Android Persistent Data Storage Douglas C. Schmidt 6 Android SQLite • Android supports SQLite, which provides a relational database for a mobile device • It’s designed to operate within a small footprint (~350kB) within a single cross-platform disk file en.wikipedia.org/wiki/SQLite
  • 7. Android Persistent Data Storage Douglas C. Schmidt 7 Android SQLite • Android supports SQLite, which provides a relational database for a mobile device • It’s designed to operate within a small footprint (<300kB) within a single cross-platform disk file • Implements most of SQL92 & supports so-called “ACID” transactions • Atomic, Consistent, Isolated, & Durable en.wikipedia.org/wiki/SQL-92
  • 8. Android Persistent Data Storage Douglas C. Schmidt 8 Android SQLite • Android supports SQLite, which provides a relational database for a mobile device • It’s designed to operate within a small footprint (<300kB) within a single cross-platform disk file • Implements most of SQL92 & supports so-called “ACID” transactions • Access to an SQLite database typically involves accessing the Android filesystem • Database operations are typically asynchronous since filesystem access can be slow • e.g., access is often made via AsyncTask, AsyncQueryHandler, CursorLoader, etc. www.vogella.com/articles/AndroidSQLite/article.html
  • 9. Android Persistent Data Storage Douglas C. Schmidt 9 SQLiteDatabase • SQLiteDatabase is the base class for working with a SQLite database in Android • It provides the insert(), update(), & delete() methods developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
  • 10. Android Persistent Data Storage Douglas C. Schmidt 10 SQLiteDatabase • SQLiteDatabase is the base class for working with a SQLite database in Android • It provides the insert(), update(), & delete() methods • It also provides the execSQL() method that can execute an SQL statement directly developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
  • 11. Android Persistent Data Storage Douglas C. Schmidt 11 SQLiteDatabase • SQLiteDatabase is the base class for working with a SQLite database in Android • Queries can be created via rawQuery() & query() methods or via the SQLiteQueryBuilder class developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html
  • 12. Android Persistent Data Storage Douglas C. Schmidt 12 ContentValues developer.android.com/reference/android/content/ContentValues.html • The ContentValues object is used by SQLiteDatabase to define key/values • The “key” represents the table column identifier & the “value” represents the content for the table record in this column
  • 13. Android Persistent Data Storage Douglas C. Schmidt 13 ContentValues developer.android.com/reference/android/content/ContentValues.html • The ContentValues object is used by SQLiteDatabase to define key/values • ContentValues can be used for inserts & updates of database entries
  • 14. Android Persistent Data Storage Douglas C. Schmidt 14 SQLiteOpenHelper • Recommended means of using SQLiteDatabase is to subclass the SQLiteOpenHelper class • In constructor call the super() method of SQLiteOpenHelper, specifying database name & current database version developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
  • 15. Android Persistent Data Storage Douglas C. Schmidt 15 SQLiteOpenHelper • Recommended means of using SQLiteDatabase is to subclass the SQLiteOpenHelper class • In constructor call the super() method of SQLiteOpenHelper, specifying database name & current database version • Override onCreate(), which is called by SQLite if the database does not yet exist • e.g., execute CREATE TABLE command developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
  • 16. Android Persistent Data Storage Douglas C. Schmidt 16 SQLiteOpenHelper • Recommended means of using SQLiteDatabase is to subclass the SQLiteOpenHelper class • In constructor call the super() method of SQLiteOpenHelper, specifying database name & current database version • Override onCreate(), which is called by SQLite if the database does not yet exist • Override onUpgrade(), which is called if the database version increases in App code to allow database schema updates developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
  • 17. Android Persistent Data Storage Douglas C. Schmidt 17 SQLiteOpenHelper • Recommended means of using SQLiteDatabase is to subclass the SQLiteOpenHelper class • Use SQLiteOpenHelper methods to open & return underlying database • e.g., getReadableDatabase() & getWriteableDatabase() to access an SQLiteDatabase object either in read or write mode, respectively developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
  • 18. Android Persistent Data Storage Douglas C. Schmidt 18 Opening an SQLite Database public class ArtistDatabaseHelper extends SQLiteOpenHelper { final private static String CREATE_CMD = "CREATE TABLE artists (" + "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT, " + "name" + " TEXT NOT NULL)"; public ArtistDatabaseHelper(Context context) { super(context, "artists_db", null, 1); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_CMD); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* ... */ } ... It’s common to create an SQLiteOpenHelper subclass for each SQL table Create the SQL table SQL commands to create a table of artists Give a name to the table Support schema evolution
  • 19. Android Persistent Data Storage Douglas C. Schmidt 19 Using an SQLite Database Via an Activity public class DatabaseExampleActivity extends ListActivity { final static String[] columns ={"_id", "name"}; static SQLiteDatabase db = null; public void onCreate(Bundle savedInstanceState) { ... ArtistDatabaseHelper dbHelper = new ArtistDatabaseHelper (getActivity().getApplicationContext()); db = dbHelper.getWritableDatabase(); insertArtists(); deleteLadyGaga(); Cursor c = readArtists(); displayArtists(c); } ... SQLiteDatabase is often put in an App singleton to simplify access Make the SQLiteOpenHelper subclass instance Create a read/write databse Perform various operations
  • 20. Android Persistent Data Storage Douglas C. Schmidt 20 Inserting Values Into an SQLite Database • Method for inserting a row into the database public long insert (String table, String nullColHack, ContentValues values) Parameters table The table to insert the row into nullColHack Optional (often null) values Map containing initial col values for row; keys are col names developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #insert(java.lang.String, java.lang.String, android.content.ContentValues)
  • 21. Android Persistent Data Storage Douglas C. Schmidt 21 Inserting Values Into an SQLite Database • Method for inserting a row into the database public long insert (String table, String nullColHack, ContentValues values) developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #insert(java.lang.String, java.lang.String, android.content.ContentValues)
  • 22. Android Persistent Data Storage Douglas C. Schmidt 22 Inserting Values Into an SQLite Database private void insertArtists() { ContentValues values = new ContentValues(); values.put("name", "Lady Gaga"); db.insert("artists", null, values); values.clear(); values.put("name", "Johnny Cash"); db.insert("artists", null, values); values.clear(); values.put("name", "Sting"); db.insert("artists", null, values); ... } “key” represents the table column identifier & the “value” represents the content for the table record in this column
  • 23. Android Persistent Data Storage Douglas C. Schmidt 23 Deleting a Row From an SQLite Database Parameters table the table to delete from whereClause optional WHERE clause to apply when deleting whereArgs Passing null deletes all rows developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #delete(java.lang.String, java.lang.String, java.lang.String[]) • Method for deleting row(s) from the database public int delete(String table, String whereClause, String[] whereArgs)
  • 24. Android Persistent Data Storage Douglas C. Schmidt 24 Deleting a Row From an SQLite Database developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #delete(java.lang.String, java.lang.String, java.lang.String[]) • Method for deleting row(s) from the database public int delete(String table, String whereClause, String[] whereArgs)
  • 25. Android Persistent Data Storage Douglas C. Schmidt 25 Deleting a Row From an SQLite Database private int deleteLadyGaga() { return db.delete("artists", "name" + "=?", new String [] {"Lady Gaga"}); } Remove Lady Gaga from the database of artists Note the use of the “whereArgs”
  • 26. Android Persistent Data Storage Douglas C. Schmidt 26 Querying an SQLite Database • You can use rawQuery() or a query() on an SQLiteDatabase public Cursor rawQuery(String sql, String[] selectionArgs) Runs the provided SQL and returns a Cursor over the result set Parameters Returns A Cursor object, which is positioned before the first entry sql the SQL query. The SQL string must not be ; terminated selectionArgs You may include ?’s in where clause in the query, which are replaced by the values from selectionArgs (the values will be bound as Strings) Cursors aren’t synchronized, see documentation for details
  • 27. Android Persistent Data Storage Douglas C. Schmidt 27 Querying an SQLite Database • You can use rawQuery() or a query() on an SQLiteDatabase public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) query() builds up a SQL SELECT statement from its component parts Parameter String table The table name to compile the query against int[] columns A list of which table columns to return ("null" returns all columns) String selection Where-clause filters for the selection of data (null selects all data) String[] selectionArgs You may include ?s in the “selection” where-clause that get replaced by the values from the selectionArgs array String[] groupBy A filter declaring how to group rows (null means rows not grouped) String[] having Filter for the groups (null means no filter) String[] orderBy Table columns used to order the data (null means no ordering) Returns A Cursor object, which is positioned before the first entry
  • 28. Android Persistent Data Storage Douglas C. Schmidt 28 Using Query() vs. rawQuery() private Cursor readArtists() { // returns all rows return db.rawQuery("SELECT _id, name FROM artists", null); } • Using rawQuery() on an SQLiteDatabase developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #rawQuery(java.lang.String, java.lang.String[])
  • 29. Android Persistent Data Storage Douglas C. Schmidt 29 Using Query() vs. rawQuery() private Cursor readArtists() { // returns all rows return db.query("artists", new String [] {"_id", "name"}, null, null, null, null, null); } private Cursor readArtists() { // returns all rows return db.rawQuery("SELECT _id, name FROM artists", null); } • Using rawQuery() on an SQLiteDatabase • Using query() on an SQLiteDatabase developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html #query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)
  • 30. Android Persistent Data Storage Douglas C. Schmidt 30 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • This allows buffering of query results efficiently since all data needn’t be loaded into memory
  • 31. Android Persistent Data Storage Douglas C. Schmidt 31 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query
  • 32. Android Persistent Data Storage Douglas C. Schmidt 32 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query • moveToFirst() & moveToNext() move between individual data rows
  • 33. Android Persistent Data Storage Douglas C. Schmidt 33 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query • moveToFirst() & moveToNext() move between individual data rows • isAfterLast() checks if the end of the query result has been reached
  • 34. Android Persistent Data Storage Douglas C. Schmidt 34 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query • moveToFirst() & moveToNext() move between individual data rows • isAfterLast() checks if the end of the query result has been reached • Provides typed get*() methods • e.g., getLong(columnIndex) & getString(columnIndex) to access column data for current position of result
  • 35. Android Persistent Data Storage Douglas C. Schmidt 35 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query • moveToFirst() & moveToNext() move between individual data rows • isAfterLast() checks if the end of the query result has been reached • Provides typed get*() methods • Provides getColumnIndexOrThrow (String) to get column index for a column name of table
  • 36. Android Persistent Data Storage Douglas C. Schmidt 36 Cursor Iterators developer.android.com/reference/android/database/Cursor.html • Query() returns a Cursor Iterator that represents result of a query & points to one row of query result • getCount() returns # of elements of the resulting query • moveToFirst() & moveToNext() move between individual data rows • isAfterLast() checks if the end of the query result has been reached • Provides typed get*() methods • Provides getColumnIndexOrThrow (String) to get column index for a column name of table • Must be closed via close()
  • 37. Android Persistent Data Storage Douglas C. Schmidt 37 Displaying an SQLite Database private void displayArtists (Cursor c) { setListAdapter( new SimpleCursorAdapter (this, R.layout.list_layout, c, new String [] {"_id", "name"}, new int[] { R.id._id, R.id.name })); } developer.android.com/reference/android/widget/SimpleCursorAdapter.html • The SimpleCursorAdapter class maps the columns to the Views based on the Cursor passed to it
  • 38. Android Persistent Data Storage Douglas C. Schmidt 38 Examining an SQLite Database • If your App creates a database it is saved by default in a directory file /DATA/data/APP_NAME/databases/FILENAME • DATA is the path that the Environment. getDataDirectory() method returns • APP_NAME is your app name • FILENAME is the name you specify in your application code for the database
  • 39. Android Persistent Data Storage Douglas C. Schmidt 39 Examining an SQLite Database • If your App creates a database it is saved by default in a directory file • You can examine this database with sqlite3 # adb shell # sqlite3 /data/data/com.android.launcher/databases/launcher.db
  • 40. Android Persistent Data Storage Douglas C. Schmidt 40 Summary • SQLite is embedded into every Android device • Using an SQLite database in Android does not require a setup procedure or administration of the database
  • 41. Android Persistent Data Storage Douglas C. Schmidt 41 Summary • SQLite is embedded into every Android device • You only have to define the SQL statements for creating & updating the database • Afterwards the database is automatically managed for you by the Android platform
  • 42. Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Android Content Providers: Introduction
  • 43. Developing Android Apps with Eclipse Douglas C. Schmidt 43 Overview of Content Providers • ContentProviders manage access to a central repository of structured data & can make an App’s data available to other Apps developer.android.com/guide/topics/providers/content-providers.html
  • 44. Developing Android Apps with Eclipse Douglas C. Schmidt 44 Overview of Content Providers • ContentProviders manage access to a central repository of structured data & can make an App’s data available to other Apps • They encapsulate the data & provide mechanisms for defining data security developer.android.com/guide/topics/providers/content-providers.html
  • 45. Developing Android Apps with Eclipse Douglas C. Schmidt 45 Overview of Content Providers • ContentProviders manage access to a central repository of structured data & can make an App’s data available to other Apps • They encapsulate the data & provide mechanisms for defining data security • Content providers are the standard interface that connects data in one process with code running in another process developer.android.com/guide/topics/providers/content-providers.html
  • 46. Developing Android Apps with Eclipse Douglas C. Schmidt 46 Overview of Content Providers • ContentProviders manage access to a central repository of structured data & can make an App’s data available to other Apps • They encapsulate the data & provide mechanisms for defining data security • Content providers are the standard interface that connects data in one process with code running in another process • Content providers support database “CRUD” operations (Create, Read, Update, Delete), where “read” is implemented as “query” developer.android.com/guide/topics/providers/content-providers.html
  • 47. Developing Android Apps with Eclipse Douglas C. Schmidt 47 Overview of Content Providers • ContentProviders manage access to a central repository of structured data & can make an App’s data available to other Apps • They encapsulate the data & provide mechanisms for defining data security • Content providers are the standard interface that connects data in one process with code running in another process • Content providers support database “CRUD” operations (Create, Read, Update, Delete), where “read” is implemented as “query” • Apps can provide Activities that allow users to query & modify the data managed by a provider developer.android.com/guide/topics/providers/content-providers.html
  • 48. Developing Android Apps with Eclipse Douglas C. Schmidt 48 Example Android ContentProviders • Android itself includes many Content Providers that manage data for • Browser – bookmarks, history • Call log – telephone usage • Contacts – contact data • MMS/SMS – Stores messages sent & received • Media – media database • UserDictionary – database for predictive spelling • Maps – previous searches • YouTube – previous searches • Many more developer.android.com/reference/android/provider/package-summary.html
  • 49. Developing Android Apps with Eclipse Douglas C. Schmidt 49 ContentProvider Data Model • A content provider typically presents data to external Apps as one or more tables • e.g., the tables found in a relational SQL database
  • 50. Developing Android Apps with Eclipse Douglas C. Schmidt 50 ContentProvider Data Model • A content provider typically presents data to external Apps as one or more tables • A row represents an instance of some type of data the provider collects • Each column in a row represents an individual piece of data collected for an instance word app id freq locale _ID mapreduce user1 100 en_US 1 precompiler user14 200 fr_FR 2 applet user2 225 fr_CA 3 const user1 255 pt_BR 4 int user5 100 en_UK 5 One provider in Android is the user dictionary, which stores the spellings of non-standard words that the user wants to keep
  • 51. Developing Android Apps with Eclipse Douglas C. Schmidt 51 Overview of ContentResolver • ContentProvider never accessed directly, but accessed indirectly via a ContentResolver • ContentProvider not created until a ContentResolver tries to access it developer.android.com/reference/android/content/ContentResolver.html
  • 52. Developing Android Apps with Eclipse Douglas C. Schmidt 52 Overview of ContentResolver • ContentProvider never accessed directly, but accessed indirectly via a ContentResolver • ContentResolvers manage & support ContentProviders • Enables use of ContentProviders across multiple Apps developer.android.com/reference/android/content/ContentResolver.html
  • 53. Developing Android Apps with Eclipse Douglas C. Schmidt 53 Overview of ContentResolver • ContentProvider never accessed directly, but accessed indirectly via a ContentResolver • ContentResolvers manage & support ContentProviders • Enables use of ContentProviders across multiple Apps • Provides additional services, such as change notification & IPC developer.android.com/reference/android/content/ContentResolver.html
  • 54. Developing Android Apps with Eclipse Douglas C. Schmidt 54 Overview of ContentResolver • ContentProvider never accessed directly, but accessed indirectly via a ContentResolver • ContentResolvers manage & support ContentProviders • Context.getContentResolver() accesses default ContentResolver ContentResolver cr = getContentResolver(); developer.android.com/reference/android/content/ContentResolver.html
  • 55. Developing Android Apps with Eclipse Douglas C. Schmidt 55 • When you query data via a ContentProvider, you don't communicate with the provider directly • Instead, you use a ContentResolver object to communicate with the provider ContentResolver vs. ContentProvider www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
  • 56. Developing Android Apps with Eclipse Douglas C. Schmidt 56 ContentResolver vs. ContentProvider • When you query data via a ContentProvider, you don't communicate with the provider directly • A call to getContentResolver(). query() is made • This method call invokes ContentResolver.query(), not ContentProvider.query() www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
  • 57. Developing Android Apps with Eclipse Douglas C. Schmidt 57 ContentResolver vs. ContentProvider • When you query data via a ContentProvider, you don't communicate with the provider directly • A call to getContentResolver(). query() is made • When this query method is invoked, the Content Resolver parses the uri argument & extracts its authority • The Content Resolver directs the request to the content provider registered with the (unique) authority by calling the Content Provider's query() method www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
  • 58. Developing Android Apps with Eclipse Douglas C. Schmidt 58 ContentResolver vs. ContentProvider • When you query data via a ContentProvider, you don't communicate with the provider directly • A call to getContentResolver(). query() is made • When this query method is invoked, the Content Resolver parses the uri argument & extracts its authority • When the Content Provider's query() method is invoked, the query is performed & a Cursor is returned (or an exception is thrown) • The resulting behavior depends on Content Provider's implementation www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html
  • 59. Developing Android Apps with Eclipse Douglas C. Schmidt 59 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider
  • 60. Developing Android Apps with Eclipse Douglas C. Schmidt 60 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider • e.g., content://authority/path/id • content - data is managed by a ContentProvider
  • 61. Developing Android Apps with Eclipse Douglas C. Schmidt 61 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider • e.g., content://authority/path/id • content - data is managed by a ContentProvider • authority – id for the content provider
  • 62. Developing Android Apps with Eclipse Douglas C. Schmidt 62 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider • e.g., content://authority/path/id • content - data is managed by a ContentProvider • authority – id for the content provider • path – 0 or more segments indicating the type of data to access
  • 63. Developing Android Apps with Eclipse Douglas C. Schmidt 63 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider • e.g., content://authority/path/id • content - data is managed by a ContentProvider • authority – id for the content provider • path – 0 or more segments indicating the type of data to access • id – specific record being requested
  • 64. Developing Android Apps with Eclipse Douglas C. Schmidt 64 Content URIs • Any URI that begins with the content:// scheme represents a resource served up by a Content Provider • e.g., content://authority/path/id • ContentProviders are a façade that offers data encapsulation via Content Uri objects used as handles • The data could be stored in a SQLite database, in flat files, retrieved off a device, be stored on some server accessed over the Internet, etc.
  • 65. Developing Android Apps with Eclipse Douglas C. Schmidt 65 Inserting Data Via ContentResolver • Use ContentResolver.insert() to insert data into a ContentProvider public final Uri insert(Uri uri, ContentValues values) • Inserts a row into a table at the given URI • If the content provider supports transactions the insertion will be atomic Parameters • uri – The uri of the table to insert into • values – The initial values for the newly inserted row, where the key is the column name for the field (passing an empty ContentValues will create an empty row) Returns • the URI of the newly created row developer.android.com/reference/android/content/ContentProvider.html #insert(android.net.Uri, android.content.ContentValues)
  • 66. Developing Android Apps with Eclipse Douglas C. Schmidt 66 Deleting Data Via ContentResolver • Use ContentResolver.delete() to delete data from a ContentProvider public final int delete(Uri uri, String where, String[] selectionArgs) • Deletes row(s) specified by a content URI. If the content provider supports transactions, the deletion will be atomic Parameters • uri – The uri of the row to delete • where – A filter to apply to rows before deleting, formatted as an SQL WHERE clause (excluding the WHERE itself) • selectionArgs – SQL pattern args Returns • The number of rows deleted developer.android.com/reference/android/content/ContentProvider.html #delete(android.net.Uri, java.lang.String, java.lang.String[])
  • 67. Developing Android Apps with Eclipse Douglas C. Schmidt 67 Inserting/Deleting via applyBatch() • ContentResolver.applyBatch() can insert (& delete) groups of data public ContentProviderResult[] applyBatch (String authority, ArrayList<ContentProviderOperation> operations) • Applies each ContentProviderOperation object & returns array of results • If all the applications succeed then a ContentProviderResult array with the same number of elements as the operations will be returned Parameters • authority –authority of the ContentProvider to apply this batch • operations – the operations to apply Returns • the results of the applications developer.android.com/reference/android/content/ContentProvider.html #applyBatch(java.util.ArrayList<android.content.ContentProviderOperation>)
  • 68. Developing Android Apps with Eclipse Douglas C. Schmidt 68 Querying a ContentResolver • Use ContentResolver. query() to retrieve data • Returns a Cursor instance for accessing results • A Cursor is an iterator over a result set developer.android.com/reference/android/content/ContentProvider.html#query (Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
  • 69. Developing Android Apps with Eclipse Douglas C. Schmidt 69 query() Parameters Compared to SQL Query query() argument SELECT keyword/parameter Notes Uri FROM table_name Uri maps to the table in the provider named table_name projection col,col,col,... projection is an array of columns that should be included for each row retrieved selection WHERE col =value selection specifies the criteria for selecting rows selectionArgs No exact equivalent in SQL Selection arguments replace the ? placeholders in the selection clause sortOrder ORDER BYcol,col,... sortOrder specifies the order in which rows appear in the returned Cursor
  • 70. Developing Android Apps with Eclipse Douglas C. Schmidt 70 Summary • A SQLite database is private to the App which creates it • If you want to share data with other App you can use a content provider
  • 71. Developing Android Apps with Eclipse Douglas C. Schmidt 71 Summary • A SQLite database is private to the App which creates it • A content provider allows App to access data • In most cases this data is stored in an SQlite database
  • 72. Developing Android Apps with Eclipse Douglas C. Schmidt 72 Summary • A SQLite database is private to the App which creates it • A content provider allows App to access data • While a content provider can be used within an App to access data, its is typically used to share data with other App
  • 73. Developing Android Apps with Eclipse Douglas C. Schmidt 73 Summary • A SQLite database is private to the App which creates it • A content provider allows App to access data • While a content provider can be used within an App to access data, its is typically used to share data with other App • App data is by default private, so a content provider is a convenient to share you data with other application based on a structured interface
  • 74. Developing Android Apps with Eclipse Douglas C. Schmidt 74 Summary • A SQLite database is private to the App which creates it • A content provider allows App to access data • While a content provider can be used within an App to access data, its is typically used to share data with other App • App data is by default private, so a content provider is a convenient to share you data with other application based on a structured interface • A content provider must be declared in the AndroidManifest.xml file