Android通讯录联系人的读取、更新、插入、删除等方法

TestContacts.Java

[java]  view plain  copy
 print ?
  1. package waga.android.study.TestContacts;  
  2. import android.app.Activity;  
  3. import android.content.ContentResolver;  
  4. import android.content.Intent;  
  5. import android.database.Cursor;  
  6. import android.os.Bundle;  
  7. import android.provider.ContactsContract;  
  8. import android.provider.ContactsContract.RawContacts;  
  9. import android.view.Menu;  
  10. import android.view.MenuInflater;  
  11. import android.view.MenuItem;  
  12. import android.widget.TextView;  
  13. public class TestContacts extends Activity  
  14. {  
  15. TextView myTextView;  
  16. String str;  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState)  
  19.     {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.         setTitle(R.string.ReadContact);  
  23.     }  
  24.      
  25.     // 创建选项菜单  
  26.     @Override  
  27.     public boolean onCreateOptionsMenu(Menu menu)  
  28.     {  
  29.      super.onCreateOptionsMenu(menu);  
  30.   MenuInflater inflater = getMenuInflater();  
  31.   inflater.inflate(R.layout.menu, menu);  
  32.     
  33.   return true;  
  34. }  
  35.     // 响应选项菜单  
  36. @Override  
  37. public boolean onOptionsItemSelected(MenuItem item)  
  38. {  
  39.   switch (item.getItemId())  
  40.   {  
  41.    // 新建联系人  
  42.          case R.id.menu_add:  
  43.          {  
  44.           // new一 个Intent对 象 , 并指定class  
  45.           Intent intent = new Intent();  
  46.           intent.setClass(this, NewContactActivity.class);  
  47.           startActivity(intent);  
  48.           return true;  
  49.    }  
  50.            
  51.          // 删除联系人  
  52.          case R.id.menu_delete:  
  53.          {  
  54.           // new一 个Intent对 象 , 并指定class  
  55.           Intent intent = new Intent();  
  56.           intent.setClass(this, DeleteContactActivity.class);  
  57.           startActivity(intent);  
  58.           return true;  
  59.    }  
  60.            
  61.          // 更新联系人  
  62.          case R.id.menu_update:  
  63.          {  
  64.           // new一 个Intent对 象 , 并指定class  
  65.           Intent intent = new Intent();  
  66.           intent.setClass(this, UpdateContactActivity.class);  
  67.           startActivity(intent);  
  68.           return true;  
  69.    }  
  70.            
  71.          // 退出  
  72.          case R.id.menu_exit:  
  73.          {  
  74.           finish();  
  75.           return true;  
  76.          }  
  77.   }  
  78.   return false;  
  79. }  
  80. @Override  
  81. protected void onResume()  
  82. {  
  83.   super.onResume();  
  84.   TextView myTextView = (TextView)findViewById(R.id.ContactsInfo);  
  85.         str = "";  
  86.           
  87.   // 读取所有的联系人  
  88.         readAllContacts();  
  89.           
  90.         myTextView.setText(str);  
  91. }  
  92. // 读取所有的联系人  
  93.     public void readAllContacts()  
  94.     {  
  95.      ContentResolver cr = getContentResolver();  
  96.      Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, nullnullnullnull);  
  97.         if (cur.getCount() > 0)  
  98.         {  
  99.          while (cur.moveToNext())  
  100.          {  
  101.           String rawContactsId = "";  
  102.              String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));  
  103.           String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));  
  104.           str += "ContactID:" + id + "\n";  
  105.           // 读取rawContactsId  
  106.           Cursor rawContactsIdCur = cr.query(RawContacts.CONTENT_URI,  
  107.          null,  
  108.          RawContacts.CONTACT_ID +" = ?",    
  109.          new String[]{id}, null);  
  110.            
  111.           if (rawContactsIdCur.moveToFirst())  
  112.           {  
  113.            rawContactsId = rawContactsIdCur.getString(rawContactsIdCur.getColumnIndex(RawContacts._ID));  
  114.            str += "RawContactsID:" + rawContactsId + "\n";  
  115.           }  
  116.           rawContactsIdCur.close();  
  117.            
  118.           str += "姓名:" + name + "\n";  
  119.            
  120.           /* 
  121.            Android文档:ContactsContract.CommonDataKinds.Phone: 
  122.         CONTENT_URI:The content:// style URI for all data records of the  CONTENT_ITEM_TYPE MIME type, combined with the associated  raw contact and aggregate contact data. 
  123.        */  
  124.            
  125.           // 读取号码  
  126.           if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)  
  127.           {  
  128.            //Uri phoneUri=Uri.parse("content://com.android.contacts/data/phones");  
  129.            // 下面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI可以用phoneUri代替  
  130.            Cursor PhoneCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,  
  131.                null,  
  132.                //ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",  
  133.                ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID +" = ?",  
  134.                new String[]{rawContactsId}, null);  
  135.            while (PhoneCur.moveToNext())  
  136.            {  
  137.             String number = PhoneCur.getString(PhoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
  138.             String numberType = PhoneCur.getString(PhoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));  
  139.             str += numberType + ":" + number + "\n";  
  140.            }  
  141.            PhoneCur.close();  
  142.           }  
  143.            
  144.           // 读取Email  
  145.           //Uri emailUri=Uri.parse("content://com.android.contacts/data/emails");  
  146.           // 下面的ContactsContract.CommonDataKinds.Email.CONTENT_URI可以用emailUri代替  
  147.           Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,  
  148.                   null,  
  149.                   ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",  
  150.                   new String[]{id}, null);  
  151.           while (emailCur.moveToNext())  
  152.           {     
  153.               String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));  
  154.               String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));  
  155.               str += emailType + ":" + email + "\n";  
  156.           }  
  157.           /*Email类型: 
  158.           1:TYPE_HOME 
  159.     2:TYPE_WORK 
  160.     3:TYPE_OTHER 
  161.     4:TYPE_MOBILE 
  162.           */  
  163.           emailCur.close();  
  164.            
  165.           // 读取备注  
  166.           String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";     
  167.           String[] noteWhereParams = new String[]{id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};  
  168.           Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);  
  169.           if (noteCur.moveToFirst())  
  170.           {  
  171.            String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));  
  172.            str += "备注:" + note + "\n";  
  173.           }  
  174.           noteCur.close();  
  175.            
  176.           // 读取邮政地址  
  177.           String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";  
  178.           String[] addrWhereParams = new String[]{id,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};  
  179.           Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);  
  180.           while(addrCur.moveToNext())  
  181.           {     
  182.               String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));  
  183.                  String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));  
  184.                  String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));     
  185.                  String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));     
  186.                  String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));     
  187.                  String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));     
  188.                  String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));  
  189.                    
  190.                  if (poBox != "")  
  191.                  {  
  192.                   str += "POBOX:" + poBox + "\n";  
  193.                  }  
  194.                    
  195.                  if (street != "")  
  196.                  {  
  197.                   str += "STREET:" + street + "\n";  
  198.                  }  
  199.                    
  200.                  if (city != "")  
  201.                  {  
  202.                   str += "CITY:" + city + "\n";  
  203.                  }  
  204.                    
  205.                  if (state != "")  
  206.                  {  
  207.                   str += "REGION:" + state + "\n";  
  208.                  }  
  209.                    
  210.                  if (postalCode != "")  
  211.                  {  
  212.                   str += "POSTCODE:" + postalCode + "\n";  
  213.                  }  
  214.                    
  215.                  if (country != "")  
  216.                  {  
  217.                   str += "COUNTRY:" + country + "\n";  
  218.                  }  
  219.                    
  220.                  if (type != "")  
  221.                  {  
  222.                   str += "TYPE:" + type + "\n";  
  223.                  }  
  224.           }  
  225.           addrCur.close();  
  226.            
  227.           // 读取即时消息  
  228.           String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";  
  229.           String[] imWhereParams = new String[]{id, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};  
  230.           Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,null, imWhere, imWhereParams, null);  
  231.           while(imCur.moveToNext())  
  232.           {  
  233.               String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));  
  234.               String imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));  
  235.               str += imType + ":" + imName + "\n";  
  236.           }  
  237.           imCur.close();  
  238.            
  239.           // 读取公司及职位  
  240.           String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";  
  241.              String[] orgWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};  
  242.              Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);     
  243.              while (orgCur.moveToNext())  
  244.              {  
  245.                  String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));  
  246.                  String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));  
  247.                  str += orgName + ":" + title + "\n";  
  248.              }  
  249.              orgCur.close();  
  250.               
  251.              str += "\n";  
  252.          }  
  253.         }  
  254.     }  
  255. }  


NewContactActivity:

[java]  view plain  copy
 print ?
  1. package waga.android.study.TestContacts;  
  2. import android.app.Activity;  
  3. import android.content.ContentUris;  
  4. import android.content.ContentValues;  
  5. import android.net.Uri;  
  6. import android.os.Bundle;  
  7. import android.provider.ContactsContract;  
  8. import android.provider.ContactsContract.RawContacts;  
  9. import android.provider.ContactsContract.CommonDataKinds.Email;  
  10. import android.provider.ContactsContract.CommonDataKinds.Im;  
  11. import android.provider.ContactsContract.CommonDataKinds.Phone;  
  12. import android.provider.ContactsContract.CommonDataKinds.StructuredName;  
  13. import android.provider.ContactsContract.Contacts.Data;  
  14. import android.view.View;  
  15. import android.widget.Button;  
  16. import android.widget.EditText;  
  17. public class NewContactActivity extends Activity  
  18. {  
  19. EditText edittext_name;  
  20. EditText edittext_number;  
  21. EditText edittext_email;  
  22. EditText edittext_qq;  
  23. Button btn_Save;  
  24. @Override  
  25.     public void onCreate(Bundle savedInstanceState)  
  26.     {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.new_contact);  
  29.         setTitle(R.string.menu_newContact);  
  30.           
  31.         edittext_name = (EditText)findViewById(R.id.EditText_name);  
  32.         edittext_number = (EditText)findViewById(R.id.EditText_number);  
  33.         edittext_email = (EditText)findViewById(R.id.EditText_email);  
  34.         edittext_qq = (EditText)findViewById(R.id.EditText_qq);  
  35.         btn_Save =(Button)findViewById(R.id.Button_Save);  
  36.           
  37.         edittext_name.setText("test-1");  
  38.         edittext_number.setText("13636431707-1");  
  39.         edittext_email.setText("[email]test1@sim.com[/email]");  
  40.         edittext_qq.setText("27015155-1");  
  41.           
  42.         btn_Save.setOnClickListener(new Button.OnClickListener()  
  43.       {  
  44.          @Override  
  45.          public void onClick(View v)  
  46.          {  
  47.           String strName = edittext_name.getText().toString();  
  48.           String strNumber = edittext_number.getText().toString();  
  49.           String strEmail = edittext_email.getText().toString();  
  50.           String strQQ = edittext_qq.getText().toString();  
  51.             
  52.           // 新建联系人  
  53.           insert(strName, strNumber, strEmail, strQQ);  
  54.             
  55.           // 结束activity  
  56.           finish();  
  57.          }  
  58.         });  
  59.     }  
  60.   
  61. // 新建联系人  
  62.     public boolean insert(String given_name, String mobile_number, String work_email, String im_qq)  
  63.     {  
  64.      try  
  65.      {  
  66.       ContentValues values = new ContentValues();  
  67.   
  68.       // 下面的操作会根据RawContacts表中已有的rawContactId使用情况自动生成新联系人的rawContactId  
  69.       Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);  
  70.       long rawContactId = ContentUris.parseId(rawContactUri);  
  71.         
  72.       // 向data表插入姓名数据  
  73.       if (given_name != "")  
  74.       {  
  75.        values.clear();  
  76.        values.put(Data.RAW_CONTACT_ID, rawContactId);  
  77.        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);  
  78.        values.put(StructuredName.GIVEN_NAME, given_name);  
  79.        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);  
  80.       }  
  81.         
  82.       // 向data表插入电话数据  
  83.       if (mobile_number != "")  
  84.       {  
  85.        values.clear();  
  86.        values.put(Data.RAW_CONTACT_ID, rawContactId);  
  87.        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);  
  88.        values.put(Phone.NUMBER, mobile_number);  
  89.        values.put(Phone.TYPE, Phone.TYPE_MOBILE);  
  90.        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);  
  91.       }  
  92.         
  93.       // 向data表插入Email数据  
  94.       if (work_email != "")  
  95.       {  
  96.        values.clear();  
  97.        values.put(Data.RAW_CONTACT_ID, rawContactId);  
  98.        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);  
  99.        values.put(Email.DATA, work_email);  
  100.        values.put(Email.TYPE, Email.TYPE_WORK);  
  101.        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);  
  102.       }  
  103.         
  104.       // 向data表插入QQ数据  
  105.       if (im_qq != "")  
  106.       {  
  107.        values.clear();  
  108.        values.put(Data.RAW_CONTACT_ID, rawContactId);  
  109.        values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);  
  110.        values.put(Im.DATA, im_qq);  
  111.        values.put(Im.PROTOCOL, Im.PROTOCOL_QQ);  
  112.        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);  
  113.       }  
  114.      }  
  115.        
  116.         catch (Exception e)   
  117.         {  
  118.             return false;  
  119.         }  
  120.         return true;  
  121. }   
  122. }  


DeleteContactActivity:

[java]  view plain  copy
 print ?
  1. package waga.android.study.TestContacts;  
  2. import android.app.Activity;  
  3. import android.content.ContentUris;  
  4. import android.os.Bundle;  
  5. import android.provider.ContactsContract.RawContacts;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. public class DeleteContactActivity extends Activity  
  10. {  
  11. EditText edittext_rawContactId;  
  12. Button btn_Delete;  
  13. @Override  
  14.     public void onCreate(Bundle savedInstanceState)  
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.delete_contact);  
  18.         setTitle(R.string.menu_deleteContact);  
  19.           
  20.         edittext_rawContactId = (EditText)findViewById(R.id.EditText_rawContactId);  
  21.         btn_Delete =(Button)findViewById(R.id.Button_Delete);  
  22.           
  23.         btn_Delete.setOnClickListener(new Button.OnClickListener()  
  24.       {  
  25.          @Override  
  26.          public void onClick(View v)  
  27.          {  
  28.           long rawContactId = Long.parseLong(edittext_rawContactId.getText().toString());  
  29.             
  30.           // 新建联系人  
  31.           delete(rawContactId);  
  32.             
  33.           // 结束activity  
  34.           finish();  
  35.          }  
  36.         });  
  37.     }  
  38.   
  39. // 删除联系人  
  40.     public void delete(long rawContactId)  
  41.     {  
  42.      getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), nullnull);  
  43.      //getContentResolver().delete(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, rawContactId), null, null);  
  44.     }  
  45. }  
  46.   
  47. ****************************  
  48. UpdateContactActivity:  
  49. package waga.android.study.TestContacts;  
  50. import android.app.Activity;  
  51. import android.content.ContentValues;  
  52. import android.os.Bundle;  
  53. import android.provider.ContactsContract;  
  54. import android.provider.ContactsContract.CommonDataKinds.Phone;  
  55. import android.view.View;  
  56. import android.widget.Button;  
  57. import android.widget.EditText;  
  58. public class UpdateContactActivity extends Activity  
  59. {  
  60. EditText edittext_rawContactId;  
  61. EditText edittext_NewNumber;  
  62. Button btn_Update;  
  63. @Override  
  64.     public void onCreate(Bundle savedInstanceState)  
  65.     {  
  66.         super.onCreate(savedInstanceState);  
  67.         setContentView(R.layout.update_contact);  
  68.         setTitle(R.string.menu_updateContact);  
  69.           
  70.         edittext_rawContactId = (EditText)findViewById(R.id.EditText_rawContactId_Delete);  
  71.         edittext_NewNumber = (EditText)findViewById(R.id.EditText_newNumber);  
  72.         btn_Update =(Button)findViewById(R.id.Button_Update);  
  73.           
  74.         btn_Update.setOnClickListener(new Button.OnClickListener()  
  75.       {  
  76.          @Override  
  77.          public void onClick(View v)  
  78.          {  
  79.           String strRawContactId = edittext_rawContactId.getText().toString();  
  80.           String strNewNumber = edittext_NewNumber.getText().toString();  
  81.             
  82.           // 更新联系人  
  83.           update(strRawContactId, strNewNumber);  
  84.             
  85.           // 结束activity  
  86.           finish();  
  87.          }  
  88.         });  
  89.     }  
  90.   
  91. // 更新联系人  
  92.     public void update(String rawRawContactId, String NewNumber)  
  93.     {  
  94.      ContentValues values = new ContentValues();  
  95.      values.put(Phone.NUMBER, NewNumber);  
  96.      values.put(Phone.TYPE, Phone.TYPE_MOBILE);  
  97.        
  98.      String Where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";  
  99.         String[] WhereParams = new String[]{rawRawContactId, Phone.CONTENT_ITEM_TYPE, };  
  100.           
  101.      getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, Where, WhereParams);  
  102.     }  
  103. }  



转载:http://blog.csdn.net/chaoyu168/article/details/49069993

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值