利用ContentProvider实现查看、添加系统联系人

一、ContentProvider是不同应用程序之间进行数据交换的标准API
开发ContentProvider的步骤:
1、定义自己的ContentProvider类继承Android提供的ContentProvider基类
2、在AndroidManifest.xml文件中绑定URL
----ContentProvider类提供了增删改查方法。
二、Uri介绍:
Uri可分为三部分:content://lzl.xxx.xxx/words
content://--->是Android所规定的
lzl.xxx.xxx:
words:资源部分,当访问者需要访问不同资源时,这部分是动态改变的
Uri提供将字符串转换成Uri对象的方法
Uri uri = Uri.parse("content://lzl.xxx.xxx/words");


三、ContentResolver操作数据
Context提供如下方法过去ContentResolver对象
---> getContentResolver()
ContentResolver操作数据的步骤如下:
1、调用Activity的ContentResolver()获取COntentResolver对象
2、根据ContentResolver的增删改查方法操作数据


------------------
使用ContentProvider管理联系人
步骤:
1、布局:定义两个按钮,查询和添加按钮
2、查询:
   2.1 用户点击查询之后,将联系人姓名、email、phone显示出来用户点击查询之后,将联系人姓名、email、phone显示出来
(通过ExpandableListView显示)
   2.2 查找联系人数据
       1.用ContentResolver获取手机联系人ContactsContract.Contacts.CONTENT_URI
  2.通过ContactsContract.CommonDataKinds.Phone.CONTENT_URI获取联系人的电话。
  3.通过ContactsContract.CommonDataKinds.Email.CONTENT_URI获取联系人邮箱
   2.3 将返回的结果通过ExpandableListView显示到界面中。
3、添加:
  3.1 获取COntentResolver对象

  3.2 调用insert方法。依次将邮箱、姓名、电话和id插入到系统表中

MainActivity.java

package lzl.edu.com.contentprovidertest;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity implements View.OnClickListener {

    private Button mBSearch,mBAdd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        mBSearch = (Button)findViewById(R.id.search_btn);
        mBAdd = (Button)findViewById(R.id.add_btn);

        mBAdd.setOnClickListener(this);
        mBSearch.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_btn:
                getNextView();
                break;
            case R.id.search_btn:  //查找联系人
                ArrayList> arrayListArrayList =  searchContacts();
                Log.i("-----", arrayListArrayList.size() + "");
                expandableView(arrayListArrayList);
                break;
        }
    }
    private void getNextView(){
        View laout = getLayoutInflater().inflate(R.layout.addcontacts,null);
        EditText mEName = (EditText)laout.findViewById(R.id.name);
        EditText mEPhone = (EditText)laout.findViewById(R.id.phone);
        EditText mEEmail = (EditText)laout.findViewById(R.id.email);

        Button mConfirm = (Button)laout.findViewById(R.id.confirm);

        final String name = mEName.getText().toString();
        final String phone = mEPhone.getText().toString();
        final String email = mEEmail.getText().toString();

        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addContact(name,phone,email);
            }
        });
        setContentView(laout);
    }
    private boolean addContact(String name,String phone,String email){
        boolean flag = false;
        //将数据添加到系统联系人中
        ContentValues values = new ContentValues();
        // 得到raw_contact_id is required
        Uri contactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI,values);
        long rawContactId = ContentUris.parseId(contactUri);
        values.clear();
        //设置mimetype is required,保存联系人姓名
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();
        //设置mimetype is required,保存联系人电话
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();
        //设置mimetype is required,保存联系人email
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Email.DATA,email);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();

        Toast.makeText(MainActivity.this,"添加成功",Toast.LENGTH_LONG).show();
        return flag;
    }
    private ArrayList> searchContacts(){
        ArrayList> arrayLists = new ArrayList>();
       final ArrayList names = new ArrayList();
        //获取手机联系人
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI
                ,null,null,null,null);
        //遍历联系人结果,获取所有联系人信息
        while (cursor.moveToNext()) {
            //获取联系人id
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            //获取联系人名字
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           if(name==null){
               name = "lzl";
           }
            names.add(name);
            //获取联系人电话
            Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null
            ,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+contactId,null,null);
            ArrayList detail = new ArrayList();
            //获取同一个联系人的 多个电话号码
            while(phone.moveToNext()){
                String number = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                detail.add(number);
            }
            phone.close();
            //获取联系人邮箱
            Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI
                    ,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+contactId,null,null);
            while (emails.moveToFirst()){
                String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                detail.add(email);
            }
            emails.close();
            arrayLists.add(detail);
        }
            cursor.close();
        return arrayLists;
    }
    private void expandableView(final ArrayList> details){
        //将布局加载到界面中
        View layout = getLayoutInflater().inflate(R.layout.myexpandablelistview,null);
        ExpandableListView expandableListView = (ExpandableListView)layout.findViewById(R.id.expandableListView);
        //利用BaseExpandableListAdapter来存储数据
        BaseExpandableListAdapter adapter = new BaseExpandableListAdapter() {
            @Override
            public int getGroupCount() {
                return details.size();
            }

            @Override
            public int getChildrenCount(int groupPosition) {
                return details.get(groupPosition).size();
            }

             //获取与给定的组相关的数据,得到details集合中元素的数据
            @Override
            public Object getGroup(int groupPosition) {
                return details.get(groupPosition);
            }
            //获取给定集合中,给定的位置元素
            @Override
            public Object getChild(int groupPosition, int childPosition) {
                return details.get(groupPosition).get(childPosition);
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return true;
            }

            @Override
            public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
                TextView textView = (TextView)getTextView();
                textView.setText(getGroup(groupPosition).toString());
                return textView;
            }
            public View getTextView(){
                View layout = getLayoutInflater().inflate(R.layout.expandableitem,null);
                TextView textView = (TextView)layout.findViewById(R.id.mytextview);
                return textView;
            }
            @Override
            public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
                TextView textView = (TextView)getTextView();
                textView.setText((String)getChild(groupPosition,childPosition));
                return textView;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {
                return true;
            }
        };
        expandableListView.setAdapter(adapter);
        new AlertDialog.Builder(MainActivity.this)
               .setView(layout).setPositiveButton("确定",null).show();
    }
}
布局很简单就不再给出了。

  其中这个例子还有些困惑,当采用真机模拟的时候,会出现OOM的异常(超内存异常)。当在虚拟机上email中填入较长字符串时,也会出现这些异常。

路过的大神,希望能够指点一二。


你可能感兴趣的:(安卓基础)