开发者社区> sealin> 正文

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

简介:
+关注继续查看

TestContacts.java:

    package waga.android.study.TestContacts;
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.provider.ContactsContract.RawContacts;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.widget.TextView;
    public class TestContacts extends Activity
    {
    TextView myTextView;
    String str;
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            setTitle(R.string.ReadContact);
        }
       
        // 创建选项菜单
        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
         super.onCreateOptionsMenu(menu);
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.layout.menu, menu);
      
      return true;
    }
        // 响应选项菜单
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
      switch (item.getItemId())
      {
       // 新建联系人
             case R.id.menu_add:
             {
              // new一 个Intent对 象 , 并指定class
              Intent intent = new Intent();
              intent.setClass(this, NewContactActivity.class);
              startActivity(intent);
              return true;
       }
             
             // 删除联系人
             case R.id.menu_delete:
             {
              // new一 个Intent对 象 , 并指定class
              Intent intent = new Intent();
              intent.setClass(this, DeleteContactActivity.class);
              startActivity(intent);
              return true;
       }
             
             // 更新联系人
             case R.id.menu_update:
             {
              // new一 个Intent对 象 , 并指定class
              Intent intent = new Intent();
              intent.setClass(this, UpdateContactActivity.class);
              startActivity(intent);
              return true;
       }
             
             // 退出
             case R.id.menu_exit:
             {
              finish();
              return true;
             }
      }
      return false;
    }
    @Override
    protected void onResume()
    {
      super.onResume();
      TextView myTextView = (TextView)findViewById(R.id.ContactsInfo);
            str = "";
            
      // 读取所有的联系人
            readAllContacts();
            
            myTextView.setText(str);
    }
    // 读取所有的联系人
        public void readAllContacts()
        {
         ContentResolver cr = getContentResolver();
         Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            if (cur.getCount() > 0)
            {
             while (cur.moveToNext())
             {
              String rawContactsId = "";
                 String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
              String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
              str += "ContactID:" + id + "\n";
              // 读取rawContactsId
              Cursor rawContactsIdCur = cr.query(RawContacts.CONTENT_URI,
             null,
             RawContacts.CONTACT_ID +" = ?",  
             new String[]{id}, null);
             
              if (rawContactsIdCur.moveToFirst())
              {
               rawContactsId = rawContactsIdCur.getString(rawContactsIdCur.getColumnIndex(RawContacts._ID));
               str += "RawContactsID:" + rawContactsId + "\n";
              }
              rawContactsIdCur.close();
             
              str += "姓名:" + name + "\n";
             
              /*
               Android文档:ContactsContract.CommonDataKinds.Phone:
            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.
           */
             
              // 读取号码
              if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
              {
               //Uri phoneUri=Uri.parse("content://com.android.contacts/data/phones");
               // 下面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI可以用phoneUri代替
               Cursor PhoneCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                   null,
                   //ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                   ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID +" = ?",
                   new String[]{rawContactsId}, null);
               while (PhoneCur.moveToNext())
               {
                String number = PhoneCur.getString(PhoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String numberType = PhoneCur.getString(PhoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                str += numberType + ":" + number + "\n";
               }
               PhoneCur.close();
              }
             
              // 读取Email
              //Uri emailUri=Uri.parse("content://com.android.contacts/data/emails");
              // 下面的ContactsContract.CommonDataKinds.Email.CONTENT_URI可以用emailUri代替
              Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                      null,
                      ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                      new String[]{id}, null);
              while (emailCur.moveToNext())
              {   
                  String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                  String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                  str += emailType + ":" + email + "\n";
              }
              /*Email类型:
              1:TYPE_HOME
        2:TYPE_WORK
        3:TYPE_OTHER
        4:TYPE_MOBILE
              */
              emailCur.close();
             
              // 读取备注
              String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";   
              String[] noteWhereParams = new String[]{id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
              Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
              if (noteCur.moveToFirst())
              {
               String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
               str += "备注:" + note + "\n";
              }
              noteCur.close();
             
              // 读取邮政地址
              String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
              String[] addrWhereParams = new String[]{id,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
              Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
              while(addrCur.moveToNext())
              {   
                  String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                     String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                     String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));   
                     String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));   
                     String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));   
                     String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));   
                     String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
                     
                     if (poBox != "")
                     {
                      str += "POBOX:" + poBox + "\n";
                     }
                     
                     if (street != "")
                     {
                      str += "STREET:" + street + "\n";
                     }
                     
                     if (city != "")
                     {
                      str += "CITY:" + city + "\n";
                     }
                     
                     if (state != "")
                     {
                      str += "REGION:" + state + "\n";
                     }
                     
                     if (postalCode != "")
                     {
                      str += "POSTCODE:" + postalCode + "\n";
                     }
                     
                     if (country != "")
                     {
                      str += "COUNTRY:" + country + "\n";
                     }
                     
                     if (type != "")
                     {
                      str += "TYPE:" + type + "\n";
                     }
              }
              addrCur.close();
             
              // 读取即时消息
              String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
              String[] imWhereParams = new String[]{id, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
              Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,null, imWhere, imWhereParams, null);
              while(imCur.moveToNext())
              {
                  String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                  String imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
                  str += imType + ":" + imName + "\n";
              }
              imCur.close();
             
              // 读取公司及职位
              String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                 String[] orgWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
                 Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);   
                 while (orgCur.moveToNext())
                 {
                     String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                     String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                     str += orgName + ":" + title + "\n";
                 }
                 orgCur.close();
                
                 str += "\n";
             }
            }
        }
    }

NewContactActivity:

package waga.android.study.TestContacts;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewContactActivity extends Activity
{
EditText edittext_name;
EditText edittext_number;
EditText edittext_email;
EditText edittext_qq;
Button btn_Save;
@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_contact);
        setTitle(R.string.menu_newContact);
        
        edittext_name = (EditText)findViewById(R.id.EditText_name);
        edittext_number = (EditText)findViewById(R.id.EditText_number);
        edittext_email = (EditText)findViewById(R.id.EditText_email);
        edittext_qq = (EditText)findViewById(R.id.EditText_qq);
        btn_Save =(Button)findViewById(R.id.Button_Save);
        
        edittext_name.setText("test-1");
        edittext_number.setText("13636431707-1");
        edittext_email.setText("[email]test1@sim.com[/email]");
        edittext_qq.setText("27015155-1");
        
        btn_Save.setOnClickListener(new Button.OnClickListener()
      {
         @Override
         public void onClick(View v)
         {
          String strName = edittext_name.getText().toString();
          String strNumber = edittext_number.getText().toString();
          String strEmail = edittext_email.getText().toString();
          String strQQ = edittext_qq.getText().toString();
          
          // 新建联系人
          insert(strName, strNumber, strEmail, strQQ);
          
          // 结束activity
          finish();
         }
        });
    }

// 新建联系人
    public boolean insert(String given_name, String mobile_number, String work_email, String im_qq)
    {
     try
     {
      ContentValues values = new ContentValues();

      // 下面的操作会根据RawContacts表中已有的rawContactId使用情况自动生成新联系人的rawContactId
      Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
      long rawContactId = ContentUris.parseId(rawContactUri);
      
      // 向data表插入姓名数据
      if (given_name != "")
      {
       values.clear();
       values.put(Data.RAW_CONTACT_ID, rawContactId);
       values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
       values.put(StructuredName.GIVEN_NAME, given_name);
       getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
      }
      
      // 向data表插入电话数据
      if (mobile_number != "")
      {
       values.clear();
       values.put(Data.RAW_CONTACT_ID, rawContactId);
       values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
       values.put(Phone.NUMBER, mobile_number);
       values.put(Phone.TYPE, Phone.TYPE_MOBILE);
       getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
      }
      
      // 向data表插入Email数据
      if (work_email != "")
      {
       values.clear();
       values.put(Data.RAW_CONTACT_ID, rawContactId);
       values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
       values.put(Email.DATA, work_email);
       values.put(Email.TYPE, Email.TYPE_WORK);
       getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
      }
      
      // 向data表插入QQ数据
      if (im_qq != "")
      {
       values.clear();
       values.put(Data.RAW_CONTACT_ID, rawContactId);
       values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
       values.put(Im.DATA, im_qq);
       values.put(Im.PROTOCOL, Im.PROTOCOL_QQ);
       getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
      }
     }
     
        catch (Exception e) 
        {
            return false;
        }
        return true;
} 
}

DeleteContactActivity:

package waga.android.study.TestContacts;
import android.app.Activity;
import android.content.ContentUris;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DeleteContactActivity extends Activity
{
EditText edittext_rawContactId;
Button btn_Delete;
@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.delete_contact);
        setTitle(R.string.menu_deleteContact);
        
        edittext_rawContactId = (EditText)findViewById(R.id.EditText_rawContactId);
        btn_Delete =(Button)findViewById(R.id.Button_Delete);
        
        btn_Delete.setOnClickListener(new Button.OnClickListener()
      {
         @Override
         public void onClick(View v)
         {
          long rawContactId = Long.parseLong(edittext_rawContactId.getText().toString());
          
          // 新建联系人
          delete(rawContactId);
          
          // 结束activity
          finish();
         }
        });
    }

// 删除联系人
    public void delete(long rawContactId)
    {
     getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null);
     //getContentResolver().delete(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, rawContactId), null, null);
    }
}

****************************
UpdateContactActivity:
package waga.android.study.TestContacts;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class UpdateContactActivity extends Activity
{
EditText edittext_rawContactId;
EditText edittext_NewNumber;
Button btn_Update;
@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_contact);
        setTitle(R.string.menu_updateContact);
        
        edittext_rawContactId = (EditText)findViewById(R.id.EditText_rawContactId_Delete);
        edittext_NewNumber = (EditText)findViewById(R.id.EditText_newNumber);
        btn_Update =(Button)findViewById(R.id.Button_Update);
        
        btn_Update.setOnClickListener(new Button.OnClickListener()
      {
         @Override
         public void onClick(View v)
         {
          String strRawContactId = edittext_rawContactId.getText().toString();
          String strNewNumber = edittext_NewNumber.getText().toString();
          
          // 更新联系人
          update(strRawContactId, strNewNumber);
          
          // 结束activity
          finish();
         }
        });
    }

// 更新联系人
    public void update(String rawRawContactId, String NewNumber)
    {
     ContentValues values = new ContentValues();
     values.put(Phone.NUMBER, NewNumber);
     values.put(Phone.TYPE, Phone.TYPE_MOBILE);
     
     String Where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] WhereParams = new String[]{rawRawContactId, Phone.CONTENT_ITEM_TYPE, };
        
     getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, Where, WhereParams);
    }
}


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
在GitHub上删除项目后,在Android Studio上传项目依然提示project is already on github
描述: 在GitHub上面上传项目,但是感觉有些问题,就想删除了重新上传。 但是在Android Studio重新上传项目时,遇到了问题,一直提示“project is already on github”   解决方案: 1、关闭Android Studio项目;   2、进入到本地项目目录,找到隐藏文件夹.
1281 0
android联系人app<一>
android通信录想必大家都不会陌生,有系统自带的联系人,也有比如qq通信录,百度通讯录,,来电通,go联系人等。每种大家可能都有有偏好喜爱,但是这里我个人推荐大家使用qq通信录、百度通讯录以及来电通。
1057 0
关于RichEdit的一些小总结(不断更新)
是的,我的做法就是插入一个RTF字符串!MsftEdit应该内部有对RTF格式字符串的管理类,RichEdit里面的数据,我们一般很难触碰到的,就算能触碰到,要去进行修改和读取也不是容易的事情,这绝对是一个不合算的事情。
1082 0
android meta-data 读取
引用:http://blog.csdn.net/dianyueneo/article/details/7427722 在AndroidManifest.xml中,元素可以作为子元素,被包含在、 、和元素中,但不同的父元素,在应用时读取的方法也不同。
662 0
Windows 8.1 应用再出发 - 磁贴的更新
原文:Windows 8.1 应用再出发 - 磁贴的更新 本篇和大家一起了解一下Windows 8.1 中磁贴的更新,我们来看看如何利用它做出更好的应用磁贴。 首先我们从展现形式上来对比一下Windows 8 与 Windows 8.1 中的磁贴: Windows 8支持两种尺寸的磁贴,正方形磁贴(150 * 150 像素)和长方形磁贴(310 * 150 像素)。
817 0
+关注
sealin
学无止境
348
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载