14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6: Data Storage, Retrieval, and Sharing<br />

194<br />

int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);<br />

String[] result = new String[cursor.getCount()];<br />

if (cursor.moveToFirst())<br />

do {<br />

// Extract the name.<br />

String name = cursor.getString(nameIdx);<br />

// Extract the phone number.<br />

String phone = cursor.getString(phoneIdx);<br />

result[cursor.getPosition()] = name + “ (“ + phone + “)”;<br />

} while(cursor.moveToNext());<br />

To run this code snippet, you need to add the READ_CONTACTS permission to your application.<br />

As well as querying the contacts database, you can use this Content Provider to modify, delete, or insert<br />

contact records.<br />

Creating a New Content Provider<br />

Create a new Content Provider by extending the abstract ContentProvider class. Override the onCreate<br />

method to open or initialize the underlying data source you’re exposing with this new provider. The skeleton<br />

code for a new Content Provider is shown below:<br />

import android.content.*;<br />

import android.database.Cursor;<br />

import android.net.Uri;<br />

import android.database.SQLException;<br />

public class MyProvider extends ContentProvider {<br />

}<br />

@Override<br />

public boolean onCreate() {<br />

// TODO: Construct the underlying database.<br />

return true;<br />

}<br />

You should also expose a public static CONTENT_URI variable that returns the full URI to this provider.<br />

Content URIs must be unique between providers, so it’s good practice to base the URI path on your<br />

package name. The general form for defi ning a Content Provider’s URI is<br />

content://com..provider./<br />

For example:<br />

content://com.paad.provider.myapp/items<br />

Content URIs can represent either of two forms. The previous URI represents a request for all values of<br />

that type (e.g., all items).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!