16 增删改查取联系人
联系人数据库位置
/data/data/com.android.proriders.contacts/database/contacts2.db
需要权限
<uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
layout下面的布局文件:
Activity的xml<LinearLayout 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" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <!-- ScrollView 只能有一个子VIew --> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="联系人名称\n联系人电话号\n联系人的邮箱" /> <Button android:id="@+id/btn_insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="MyClick" android:text="添加联系人" /> <Button android:id="@+id/btn_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="MyClick" android:text="删除联系人" /> <Button android:id="@+id/btn_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="MyClick" android:text="修改联系人" /> </LinearLayout> </ScrollView> </LinearLayout>
- MainActivity.java代码:
package com.qf.day16_contentresolver_contacts_demo4;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.qf.day16_contentresolver_contacts_demo4.utils.MyContactsHelper;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
queryContacts();
}
public void MyClick(View v) {
switch (v.getId()) {
case R.id.btn_insert:// 添加数据
Map<String, Object> map = new HashMap<String, Object>();
map.put("display_name", "liyifei");
map.put("phone", "110");
map.put("email", "110@qq.com");
MyContactsHelper.insertData(getContentResolver(), map);
break;
case R.id.btn_delete:// 删除数据
boolean bl = MyContactsHelper.deleteData(getContentResolver(),
"liyifei");
if (bl) {
Toast.makeText(MainActivity.this, "删除符合条件的数据成功", 0).show();
} else {
Toast.makeText(MainActivity.this, "删除符合条件的数据失败", 0).show();
}
break;
case R.id.btn_update:// 修改数据
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("display_name", "zhangsan");
map1.put("phone", "10086");
map1.put("email", "10086@qq.com");
boolean flag = MyContactsHelper.updateData(getContentResolver(),
13, map1);
if (flag) {
Toast.makeText(MainActivity.this, "修改数据成功", 0).show();
} else {
Toast.makeText(MainActivity.this, "修改数据失败", 0).show();
}
break;
default:
break;
}
// 查询数据
queryContacts();
}
public void queryContacts() {
tv.setText("");
// 获取联系人的数据
List<Map<String, Object>> list = MyContactsHelper
.queryData(getContentResolver());
// 获取联系人的所有内容
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
// 展示联系人名称
String displayName = (String) map.get("display_name");
tv.append(displayName + "\n");
// 展示电话号
List<String> phonelist = (List<String>) map.get("phones");
for (int j = 0; j < phonelist.size(); j++) {
tv.append(phonelist.get(j) + "\n");
}
// 展示电话号
List<String> emaillist = (List<String>) map.get("emails");
for (int j = 0; j < emaillist.size(); j++) {
tv.append(emaillist.get(j) + "\n");
}
tv.append("\n");
}
}
}
增删改查逻辑代码:
MyContactsHelper.javapackage com.qf.day16_contentresolver_contacts_demo4.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; /** * 联系人的帮助类 做增删改查 * @author sxy * */ public class MyContactsHelper { // ContentResolver是通过uri来获取数据的, // 电话号有电话号的uri // 邮箱有邮箱的uri // data有data的uri // 这一系列uri是contentprovider自己定义的,我们只是调用 private static String uri_rawcontacts = "content://com.android.contacts/raw_contacts"; private static String uri_contacts_phones = "content://com.android.contacts/data/phones"; private static String uri_contacts_emails = "content://com.android.contacts/data/emails"; private static String uri_contacts_data = "content://com.android.contacts/data"; /** * 修改数据 * @param contentResolver */ public static boolean updateData(ContentResolver contentResolver,int id,Map<String, Object> map){ ContentValues values = new ContentValues(); /*这部其实不用写 data表修改会影响raw_contacts //将raw_contacts表中名字修改 values.put("display_name", map.get("display_name").toString()); values.put("display_name_alt", map.get("display_name").toString()); values.put("sort_key", map.get("display_name").toString()); values.put("sort_key_alt", map.get("display_name").toString()); */ int num = contentResolver.update(Uri.parse(uri_rawcontacts), values, "_id = ?", new String[]{id+""}); //修改data表中 姓名 values.clear(); values.put("data1", map.get("display_name").toString()); values.put("data2", map.get("display_name").toString()); int num2 = contentResolver.update(Uri.parse(uri_contacts_data), values, "raw_contact_id =? and mimetype_id = ? ", new String[]{id+"","7"}); //修改data电话号 values.clear(); values.put("data1", map.get("phone").toString()); values.put("data2", 2); int num3 = contentResolver.update(Uri.parse(uri_contacts_data), values, "raw_contact_id =? and mimetype_id = ? ", new String[]{id+"","5"}); //修改data邮箱 values.clear(); values.put("data1", map.get("email").toString()); values.put("data2", 1); int num4 = contentResolver.update(Uri.parse(uri_contacts_data), values, "raw_contact_id =? and mimetype_id = ? ", new String[]{id+"","1"}); if(num>0&&num2>0&&num3>0&&num4>0){ return true; } return false; } /** * 删除数据 返回值 是否有符合条件的数据 * @param contentResolver * @param displayName * @return */ public static boolean deleteData(ContentResolver contentResolver,String displayName){ int num = contentResolver.delete(Uri.parse(uri_rawcontacts), "display_name = ?", new String[]{displayName}); if(num>0){ return true; }else{ return false; } } /** * 插入数据 * 1,在raw_contacts表中添加一条空的数据 为了得到一个id * 2,通过id添加相应的数据 */ public static void insertData(ContentResolver contentResolver,Map<String,Object> map){ //1,在raw_contacts表中添加一条空的数据 为了得到一个id ContentValues values = new ContentValues(); //在data表修改名字会修改raw_contacts名字 Uri newUri = contentResolver.insert(Uri.parse(uri_rawcontacts), values); long id = ContentUris.parseId(newUri); //2,通过id添加相应的数据 //往data表添加联系人的名称 values.clear(); values.put("raw_contact_id", id); //data没有此字段 是内容提供者根据你mimetype的换算出 data表中mimetype_id values.put("mimetype", "vnd.android.cursor.item/name"); values.put("data1", map.get("display_name").toString()); values.put("data2", map.get("display_name").toString()); contentResolver.insert(Uri.parse(uri_contacts_data), values); //往data表添加联系人的电话 values.clear(); values.put("raw_contact_id", id); values.put("mimetype", "vnd.android.cursor.item/phone_v2"); values.put("data1", map.get("phone").toString()); values.put("data2", 2); contentResolver.insert(Uri.parse(uri_contacts_data), values); //往data表添加联系人的邮箱 values.clear(); values.put("raw_contact_id", id); values.put("mimetype", "vnd.android.cursor.item/email_v2"); values.put("data1", map.get("email").toString()); values.put("data2", 1); contentResolver.insert(Uri.parse(uri_contacts_data), values); } //查询数据 public static List<Map<String, Object>> queryData(ContentResolver contentResolver){ List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); //查询联系人id Cursor contactCursor= contentResolver.query( Uri.parse(uri_rawcontacts), new String[]{"_id","display_name"}, null, null, null); //查询联系人名称 联系人的电话 联系人的邮箱 while(contactCursor.moveToNext()){ Map<String, Object> map = new HashMap<String, Object>(); int contactsId = contactCursor.getInt(contactCursor.getColumnIndex("_id")); String displayName = contactCursor.getString(contactCursor.getColumnIndex("display_name")); //将联系人的id和联系人的名字存起来了 map.put("_id", contactsId); map.put("display_name", displayName); //获取电话号 (本质还是data表) Cursor phoneCursor = contentResolver.query(Uri.parse(uri_contacts_phones), new String[]{"raw_contact_id","data1"}, "raw_contact_id = ?", new String[]{contactsId+""}, null); //如果一个人有多个电话号 存在当前List List<String> phoneList = new ArrayList<String>(); //获取联系人电话号 电话号可能有多个 while(phoneCursor.moveToNext()){ String phoneNum = phoneCursor.getString(phoneCursor.getColumnIndex("data1")); phoneList.add(phoneNum); } //存放电话号码(可能多个)(本质还是data表) map.put("phones", phoneList); if(phoneCursor !=null){ phoneCursor.close(); } //联系人邮箱 (本质还是data表) Cursor emailCursor = contentResolver.query(Uri.parse(uri_contacts_emails), new String[]{"raw_contact_id","data1"}, "raw_contact_id = ?", new String[]{contactsId+""}, null); //如果有多个邮箱 存在集合中(本质还是data表) List<String> emailList = new ArrayList<String>(); while(emailCursor.moveToNext()){ String email = emailCursor.getString(emailCursor.getColumnIndex("data1")); emailList.add(email); } map.put("emails", emailList); if(emailCursor!=null){ emailCursor.close(); } list.add(map); } if(contactCursor!=null){ contactCursor.close(); } return list; } }
读取联系人的另一种方式
java代码:
package com.fmy.as; import android.app.Activity; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MainActivity extends Activity { // display_name返回名字 // data1返回号码 private Uri contactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; private ContentResolver resolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView lv = (ListView) findViewById(R.id.lv); resolver = getContentResolver(); Cursor cursor = resolver.query(contactsUri, null, null, null, null); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, new String[] { "display_name", "data1" }, new int[] { R.id.name, R.id.number }, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); int columnCount = cursor.getColumnCount(); String[] columnNames = cursor.getColumnNames(); lv.setAdapter(adapter); } }
Layout布局文件
Activity的布局文件<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.fmy.as.MainActivity" > <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
ListView的布局填充
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/number" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>