Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 7. Content Providers > USING A CONTENT PROVIDER

7.2. USING A CONTENT PROVIDER

The best way to understand content providers is to actually use one. The following Try It Out shows how you can use a content provider from within your Android application.

TRY IT OUT: Using the Contacts Content Provider

codefile Provider.zip available for download at Wrox.com

  1. Using Eclipse, create a new Android project and name it as shown in Figure 7-1.

    Figure 7-1. FIGURE 7-1

  2. Add the following statements in bold to the main.xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    >
    
        <ListView
            android:id="@+id/android:list"

    android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:stackFromBottom="false"
            android:transcriptMode="normal"
            />
        <TextView
            android:id="@+id/contactName"
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:id="@+id/contactID"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
           />
    <LinearLayout>

  3. In the MainActivity.java class, code the following:

    package net.learn2develop.Provider;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    importandroid.app.ListActivity;
    importandroid.database.Cursor;
    importandroid.net.Uri;
    importandroid.provider.ContactsContract;
    importandroid.widget.SimpleCursorAdapter;
    
    public class MainActivity extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Uri allContacts = Uri.parse("content://contacts/people");
    
            Cursor c = managedQuery(allContacts,null,null,null,null);
    
            String[] columns = newString[] {
                ContactsContract.Contacts.DISPLAY_NAME
                ContactsContract.Contacts._ID};
            int[] views =new int[] {R.id.contactName, R.id.contactID};
    
            SimpleCursorAdapter adapter =
                newSimpleCursorAdapter(this, R.layout.main, c, columns, views);
            this.setListAdapter(adapter);
        }
    }
    
    					  

  4. Add the following statements in bold to the AndroidManifest.xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.learn2develop.Provider"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".MainActivity"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
        </application>
        <uses-sdk android:minSdkVersion="7" />
        <uses-permission android:name="android.permission.READ_CONTACTS">
        </uses-permission>
    </manifest>
    
    					  

  5. Launch an AVD and create a few contacts in the Android Emulator (see Figure 7-2).

    Figure 7-2. FIGURE 7-2

  6. Press F11 to debug the application on the Android Emulator. Figure 7-3 shows the activity displaying the list of contacts you just created.

    Figure 7-3. FIGURE 7-3

How It Works

In this example, you retrieved all the contacts stored in the Contacts application and displayed them in the ListView.

The managedQuery() method of the Activity class retrieves a managed cursor. A managed cursor handles all the work of unloading itself when the application pauses and requerying itself when the application restarts.

The statement

Cursor c = managedQuery(allContacts, null, null, null, null);

is equivalent to

Cursor c = getContentResolver().query(allContacts, null, null, null, null);
startManagingCursor(c); //---allows the activity to manage the Cursor's
                        // lifecyle based on the activity's lifecycle---

The getContentResolver() method returns a ContentResolver object, which helps to resolve a content URI with the appropriate content provider.

The SimpleCursorAdapter object maps a cursor to TextViews (or ImageViews) defined in your XML file (main.xml). It maps the data (as represented by columns) to views (as represented by views):

String[] columns = new String[] {
    ContactsContract.Contacts.DISPLAY_NAME
    ContactsContract.Contacts._ID};

int[] views = new int[] {R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter =
            new SimpleCursorAdapter(this, R.layout.main, c, columns, views);
        this.setListAdapter(adapter);

					  

Note that in order for your application to access the Contacts application, you need to have the READ_CONTACTS permission in your AndroidManifest.xml file.



  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint