android数据提供者ContentProvider

ContentProvider的主要功能是存储并检索数据以及向其他应用程序提供访问数据的接口

我们来做个简单的例子,检索手机的联系人信息

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ssln.contentresolver.MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

</RelativeLayout>

MainActivity.java

 

package com.ssln.contentresolver;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    
    //要查询的字段
    String[] columns={People._ID,People.NAME};

    //查询联系人的URI
    Uri contactUri=People.CONTENT_URI;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView tv=(TextView)findViewById(R.id.tv);
        tv.setText("ID\tName\n"+getContactData());
    }
    private String getContactData(){
        String result="";
        ContentResolver resolver=getContentResolver();
        Cursor cursor=resolver.query(contactUri, columns, null, null, null);
        int idIndex=cursor.getColumnIndex(People._ID);
        int nameIndex=cursor.getColumnIndex(People.NAME);
        for(cursor.moveToFirst();(!cursor.isAfterLast());cursor.moveToNext()){
            result+=cursor.getString(idIndex)+"\t";
            result+=cursor.getString(nameIndex)+"\n";
        }
        cursor.close();
        return result;
    }

}

 

记得加入访问联系人的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ssln.contentresolver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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>

</manifest>

 看下效果

 

posted @ 2014-10-08 13:59  似水v流年  阅读(275)  评论(0编辑  收藏  举报