0% found this document useful (0 votes)
301 views21 pages

Android Application Development: Content Provider

The document discusses Android content providers. Key points: 1. Content providers allow data to be shared across applications by making it accessible through a common interface and data model. 2. The main Android components are activities, services, broadcast receivers, and content providers. Content providers manage access to structured data. 3. Content providers expose data through a URI and standard CRUD (create, read, update, delete) methods. Applications can query, modify, add, and delete records through the provider.

Uploaded by

Abdul Raouf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
301 views21 pages

Android Application Development: Content Provider

The document discusses Android content providers. Key points: 1. Content providers allow data to be shared across applications by making it accessible through a common interface and data model. 2. The main Android components are activities, services, broadcast receivers, and content providers. Content providers manage access to structured data. 3. Content providers expose data through a URI and standard CRUD (create, read, update, delete) methods. Applications can query, modify, add, and delete records through the provider.

Uploaded by

Abdul Raouf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Android Application Development

Content Provider
Application Building Blocks Android Component

• UI Component Typically
Activity Corresponding to one screen.

• Responds to notifications or status


Intent Receiver changes. Can wake up your process.

• Faceless task that runs in the


Service background.

ContentProvider • Enable applications to share data.


Application Building Blocks Android Component

Activities Services
1. Provides User Interface 1. No User Interface
2. Usually represents a Single 2. Runs in Background
Screen
3. Extends the Service Base Class
3. Can contain one/more Views
4. Extends the Activity Base class

Application= Set of Android Components


Intent/Broadcast Receiver Content Provider
1. Receives and Reacts to 1. Makes application data
broadcast Intents available to other apps

2. No UI but can start an Activity 2. Data stored in SQLite database


3. Extends the BroadcastReceiver 3. Extends the ContentProvider
Base Class Base class
Android Content Provider Basics

• There are no common storage area that all Android application can
access.
• The only way: to share data across applications: Content Provider
• Content providers store and retrieve data and make it accessible to all
applications.
Content Provider Android Component
Content Provider Android Component
Android Content Provider Basics

Android ships with a number of content providers for common data types:
1. Audio
2. Video
3. Images
4. Personal contact information etc

Content Provider provides the way to share the data between multiple applications.

For example, contact data is used by multiple applications (Dialer, Messaging etc.)
and must be stored in Content Provider to have common access.

A content provider is a class that implements a standard set of methods to let other
applications store and retrieve the type of data that is handled by that content provider.
Android Content Provider Basics

Here are some of Android's most useful built-in content providers, along
with a description of the type of data they're intended to store

Application can perform following operations on content provider -


1. Querying data
2. Modifying records
3. Adding records
4. Deleting records
Querying Data (Data Model) Android Content Provider

Content providers expose their data as a simple table on a database model, where
each row is a record and each column is data of a particular type and meaning.

For example, information about people and their phone numbers might be exposed
as follows:

Every record includes a numeric _ID field that uniquely identifies the record within
the table. IDs can be used to match records in related tables — for example, to
find a person's phone number in one table and pictures of that person in another.

A query returns a Cursor object that can move from record to record and column
to column to read the contents of each field. It has specialized methods for reading
each type of data. So, to read a field, you must know what type of data the field
contains.
Querying Data (Content Provider : URI) Android Content Provider

1. Each content provider exposes a public URI that uniquely identifies its data set.
2. A content provider that controls multiple data sets (multiple tables) exposes a
separate URI for each one.
3. All URIs for providers begin with the string "content://".
The content: scheme identifies the data as being controlled by a content provider.

URI samples:
<standard_prefix>://<authority>/<data_path>/<id>

For example, to retrieve all the bookmarks stored by our web browsers (in Android):
content://browser/bookmarks

Similarly, to retrieve all the contacts stored by the Contacts application:


content://contacts/people

To retrieve a particular contact, you can specify the URI with a specific ID:
content://contacts/people/3
Querying Data (Content Provider : URI) Android Content Provider

o we need three pieces of information to query a content provider:


1. The URI that identifies the provider
2. The names of the data fields you want to receive
3. The data types for those fields

If we are querying a particular record, you also need the ID for that record.

Some more examples:


content://media/internal/images URI return the list of all internal images on the device.
content://contacts/people/ URI return the list of all contact names on the device.
content://contacts/people/45 URI return the single result row, the contact with ID=45.
Querying Data (Content Provider : URI) Android Content Provider

• Although this is the general form of the query, query URIs are arbitrary and
confusing.
• For this android provide list of helper classes in android.provider package that define
these query Strings.

So we do not need to know the actual URI value for different data types.
So it will be easy to query data.

content://media/internal/images/  MediaStore.Images.Media.INTERNAL_CONTENT_URI
content://contacts/people/  Contacts.People.CONTENT_URI
content://contacts/people/45 Uri person = ContentUris.withAppendedId(People.CONTENT_URI, 23);

To query about specific record we have to use same CONTENT_URI and must append
specific ID.
Querying Data (Content Provider : URI) Android Content Provider

Here is how we can query for data:


Cursor cur = managedQuery(uri, null, null, null, null);

Parameters:
1. URI
2. The names of the data columns that should be returned. A null value
returns all columns.
3. A filter detailing which rows to return, formatted as an SQL WHERE clause
(excluding the WHERE itself). A null value returns all rows.
4. Selection arguments
5. A sorting order for the rows that are returned, formatted as an
SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns
the records in the default order for the table, which may be unordered.

Add READ_CONTACTS permission


Querying Data (Content Provider : URI) Android Content Provider

• Use ContentResolver.query() to retrieve data


• Method returns a Cursor instance for accessing results

Cursor query(
Uri uri, // ContentProvider Uri
String[] projection // Columns to retrieve
String selection // SQL selection pattern
String[] selectionArgs // SQL pattern args
String sortOrder // Sort order
)
Querying Data (Code) Android Content Provider

public class MainActivity extends Activity { @Override protected void


onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); String[] contacts =
readContacts();
ArrayAdapter<String> arrayAdapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
contacts);
setListAdapter(arrayAdapter);
}
private void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null,null,null,null);
String[] record = new String[cur.getCount()];
int a=0;
if(cur.getCount() != 0) {
while (cur.moveToNext()) {
String id =
cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
Querying Data (Code) Android Content Provider

String Name =
cur.getString(cur.getColumnIndex( ContactsContract.Contacts.DI
SPLAY_NAME ));
if(Integer.parseInt(cur.getString(
cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER
))) > 0) {
Cursor pCur =
cr.query(ContactsContract.CommonDataKinds.Phone.
CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ ID + "
= ?", new String[]{id},null);
while (pCur.moveToNext()) {
String Phone = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)) ;
Log.i(MainActivity.this + " ", "Name: " + Name + "Number: "
+ Phone);
record[i] = Name + "\n" + Phone;
}
i++;
}}}
return record;
Querying Data (Content Provider: Query Example) Android Content Provider

Now, We run the app and in emulator we see a black screen as the emulator
has no contact
data:
Querying Data (Content Provider: Query Example) Android Content Provider

If we run the app

App 1 App 2
(Contacts) (our app)

Contacts Content Provider


Querying Data (Deleting Data) Android Content Provider

• Use ContentResolver.delete() to delete data

public final int delete (


Uri url, // content Uri
String where, // SQL selection pattern
String[] selectionArgs // SQL pattern args
)
Querying Data (Deleting Data) Android Content Provider

private void deleteContact(String name) {


ContentResolver resolver = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME+ " = ? ";
String[] arg = new String[]{name};
ArrayList<ContentProviderOperation> ops = new
ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newDelete(
ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where,arg)
.build());
try {
resolver.applyBatch(ContactsContract.AUTHORITY,ops);

}catch (RemoteException e){


e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}

}
Querying Data (Insert New Contact) Android Content Provider

• Use ContentResolver. newInsert() to delete data

public final int delete (


Uri url, // content Uri
ACCOUNT_TYPE, // Account Type e.g
[email protected]
ACCOUNT_NAME // “com.what”
)
If ACCOUNT_TYPE = null and
ACCOUNT_NAME = null then it’s a local
contact

You might also like