1. 程式人生 > >利用ContentProvider實現檢視、新增系統聯絡人

利用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<ArrayList<String>> 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<ArrayList<String>> searchContacts(){
        ArrayList<ArrayList<String>> arrayLists = new ArrayList<ArrayList<String>>();
       final ArrayList<String> names = new ArrayList<String>();
        //獲取手機聯絡人
        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<String> detail = new ArrayList<String>();
            //獲取同一個聯絡人的 多個電話號碼
            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<ArrayList<String>> 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中填入較長字串時,也會出現這些異常。

路過的大神,希望能夠指點一二。