<?xml version="1.0" enCoding="utf-8"?>
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"
androID:layout_wIDth="fill_parent"
androID:layout_height="fill_parent"
androID:background="#FFD3D7DF"
androID:orIEntation="vertical"
androID:padding="0dip" >
<relativeLayout
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:layout_marginleft="3dip"
androID:layout_marginRight="3dip"
androID:layout_margintop="3dip" >
<EditText
androID:ID="@+ID/search_vIEw"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:hint="@string/hint_search_contacts"
androID:paddingleft="32dip"
androID:singleline="true"
androID:textSize="16sp" />
<ImageVIEw
androID:layout_wIDth="wrap_content"
androID:layout_height="wrap_content"
androID:layout_alignleft="@ID/search_vIEw"
androID:layout_centerVertical="true"
androID:layout_marginleft="3dip"
androID:src="@drawable/contacts" />
</relativeLayout>
<ListVIEw
androID:ID="@+ID/contact_List"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:layout_marginBottom="0dip"
androID:layout_marginleft="0dip"
androID:layout_marginRight="0dip"
androID:layout_margintop="0dip"
androID:layout_weight="1.0"
androID:cachecolorHint="#00000000"
androID:divIDer="#00000000"
androID:divIDerHeight="0.1px"
androID:fadingEdge="none"
androID:footerdivIDersEnabled="false"
androID:ListSelector="@null"
androID:paddingBottom="0dip"
androID:paddingleft="0dip"
androID:paddingRight="0dip"
androID:paddingtop="0dip" />
</linearLayout>
复制代码 代码如下:
<?xml version="1.0" enCoding="utf-8"?>
<linearLayout
xmlns:androID="http://schemas.androID.com/apk/res/androID"
androID:orIEntation="horizontal"
androID:layout_height="wrap_content"
androID:layout_wIDth="fill_parent"
androID:paddingtop="2dip"
androID:paddingBottom="2dip"
androID:background="@color/List_item_background">
<ImageVIEw
androID:ID="@+ID/photo"
androID:layout_height="wrap_content"
androID:layout_wIDth="wrap_content"
androID:layout_marginleft="5dip"
androID:layout_gravity="center_vertical"
androID:layout_weight="1"
androID:src="@drawable/default_avatar"
/>
<linearLayout
androID:orIEntation="vertical"
androID:layout_height="wrap_content"
androID:layout_wIDth="wrap_content"
androID:layout_gravity="center_vertical"
androID:layout_marginleft="5dip"
androID:layout_weight="100">
<TextVIEw androID:ID="@+ID/text1"
androID:typeface="serif"
androID:singleline="true"
/>
<linearLayout
androID:orIEntation="horizontal"
androID:layout_height="wrap_content"
androID:layout_wIDth="wrap_content"
androID:layout_margintop="3dip">
<TextVIEw androID:ID="@+ID/text2"
androID:typeface="serif"
androID:singleline="true"
/>
<TextVIEw androID:ID="@+ID/text3"
androID:ellipsize="marquee"
androID:layout_marginleft="3dip"
androID:marqueeRepeatlimit="marquee_forever"
androID:scrollHorizontally="true"
/>
</linearLayout>
</linearLayout>
</linearLayout>
然后是点击事件:(点击后要把选择的联系人号码返回到输入框里)
// 获取联系人按钮对象并绑定onClick单击事件
phonebutton = (button) findVIEwByID(R.ID.find_phone);
phonebutton.setonClickListener(new OnClickListener() {
public voID onClick(VIEw v) {
// 从联系人选择号码,再通过onActivityResult()方法处理回调结果
Intent intent = new Intent(context,ContactsActivity.class);
startActivityForResult(intent,REQUEST_CODE);
}
});
/**
* 选择联系人的回调处理函数
*/
@OverrIDe
public voID onActivityResult(int reqCode,int resultCode,Intent data) {
super.onActivityResult(reqCode,resultCode,data);
if (resultCode == RESulT_OK) {
switch (reqCode) {
case REQUEST_CODE:
String phone = data.getStringExtra("phone");
phoneEditText.setText(phone);
break;
}
}
}
复制代码 代码如下:
/**
* 显示用户手机上的联系人
*
* @author Mr.Z
* @time 2012-3-21
*
*/
public class ContactsActivity extends Activity {
private Context ctx = ContactsActivity.this;
private TextVIEw topTitleTextVIEw;
private ListVIEw ListVIEw = null;
List<HashMap<String,String>> contactsList = null;
private EditText contactsSearchVIEw;
private ProgressDialog progressDialog = null;
// 数据加载完成的消息
private final int MESSAGE_SUCC_LOAD = 0;
// 数据查询完成的消息
private final int MESSAGE_SUCC_query = 1;
private Handler handler = new Handler() {
@OverrIDe
public voID handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MESSAGE_SUCC_LOAD:
ListVIEw.setAdapter(new ContactsAdapter(ctx));
progressDialog.dismiss();
break;
case MESSAGE_SUCC_query:
ListVIEw.setAdapter(new ContactsAdapter(ctx));
break;
}
}
};
protected voID onCreate(Bundle savedInstanceState) {
requestwindowFeature(Window.FEATURE_NO_Title);
getwindow().setFlags(WindowManager.LayoutParams.FLAG_FulLSCREEN,WindowManager.LayoutParams.FLAG_FulLSCREEN);
super.onCreate(savedInstanceState);
this.setContentVIEw(R.layout.contacts);
// 使用ListVIEw显示联系人
ListVIEw = (ListVIEw) findVIEwByID(R.ID.contact_List);
loadAndSaveContacts();
// 绑定ListVIEw item的单击事件
ListVIEw.setonItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
public voID onItemClick(AdapterVIEw<?> adapterVIEw,VIEw vIEw,int position,long _ID) {
HashMap<String,String> map = (HashMap<String,String>) adapterVIEw.getItemAtposition(position);
String phone = map.get("phone");
// 对手机号码进行预处理(去掉号码前的+86、首尾空格、“-”号等)
phone = phone.replaceAll("^(\\+86)","");
phone = phone.replaceAll("^(86)","");
phone = phone.replaceAll("-","");
phone = phone.trim();
// 如果当前号码并不是手机号码
if (!SaleUtil.isValIDPhoneNumber(phone))
SaleUtil.createDialog(ctx,R.string.dialog_Title_tip,getString(R.string.alert_contacts_error_phone));
else {
Intent intent = new Intent();
intent.putExtra("phone",phone);
setResult(RESulT_OK,intent);
// 关闭当前窗口
finish();
}
}
});
contactsSearchVIEw = (EditText) findVIEwByID(R.ID.search_vIEw);
contactsSearchVIEw.addTextChangedListener(new TextWatcher() {
public voID afterTextChanged(Editable s) {
}
public voID beforeTextChanged(CharSequence s,int start,int count,int after) {
}
public voID onTextChanged(CharSequence s,int before,int count) {
queryContacts(s.toString());
}
});
}
/**
* 加载并存储联系人数据
*/
private voID loadAndSaveContacts() {
progressDialog = ProgressDialog.show(ctx,null,"正在加载联系人数据...");
new Thread() {
@OverrIDe
public voID run() {
// 获取联系人数据
contactsList = findContacts();
// 临时存储联系人数据
DBHelper.saveContacts(ctx,contactsList);
// 发送消息通知更新UI
handler.sendEmptyMessage(MESSAGE_SUCC_LOAD);
}
}.start();
}
/**
* 根据条件从本地临时库中获取联系人
*
* @param keyWord 查询关键字
*/
private voID queryContacts(final String keyWord) {
new Thread() {
@OverrIDe
public voID run() {
// 获取联系人数据
contactsList = DBHelper.findContactsByCond(ctx,keyWord);
// 发送消息通知更新UI
handler.sendEmptyMessage(MESSAGE_SUCC_query);
}
}.start();
}
/**
* 获取手机联系人信息
*
* @return List<HashMap<String,String>>
*/
public List<HashMap<String,String>> findContacts() {
List<HashMap<String,String>> List = new ArrayList<HashMap<String,String>>();
// 查询联系人
Cursor contactsCursor = ctx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,PhoneLookup.disPLAY_name + " ColLATE LOCAliZED ASC");
// 姓名的索引
int nameIndex = 0;
// 联系人姓名
String name = null;
// 联系人头像ID
String photoID = null;
// 联系人的ID索引值
String contactsID = null;
// 查询联系人的电话号码
Cursor phoneCursor = null;
while (contactsCursor.movetoNext()) {
nameIndex = contactsCursor.getColumnIndex(PhoneLookup.disPLAY_name);
name = contactsCursor.getString(nameIndex);
photoID = contactsCursor.getString(contactsCursor.getColumnIndex(PhoneLookup.PHOTO_ID));
contactsID = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts._ID));
phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactsID,null);
// 遍历联系人号码(一个人对应于多个电话号码)
while (phoneCursor.movetoNext()) {
HashMap<String,String> phoneMap = new HashMap<String,String>();
// 添加联系人姓名
phoneMap.put("name",name);
// 添加联系人头像
phoneMap.put("photo",photoID);
// 添加电话号码
phoneMap.put("phone",phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
// 添加号码类型(住宅电话、手机号码、单位电话等)
phoneMap.put("type",getString(ContactsContract.CommonDataKinds.Phone.getTypeLabelResource(phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)))));
List.add(phoneMap);
}
phoneCursor.close();
}
contactsCursor.close();
return List;
}
/**
* 获取联系人头像
*
* @param context 上下文环境
* @param photoID 头像ID
* @return Bitmap
*/
public static Bitmap getPhoto(Context context,String photoID) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.default_avatar);
if (photoID != null && "".equals(photoID)) {
String[] projection = new String[] { ContactsContract.Data.DATA15 };
String selection = "ContactsContract.Data._ID = " + photoID;
Cursor cur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,projection,selection,null);
if (cur != null) {
cur.movetoFirst();
byte[] contactIcon = null;
contactIcon = cur.getBlob(cur.getColumnIndex(ContactsContract.Data.DATA15));
if (contactIcon != null) {
bitmap = BitmapFactory.decodeByteArray(contactIcon,contactIcon.length);
}
}
}
return bitmap;
}
/**
* 自定义联系人Adapter
*/
class ContactsAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public ContactsAdapter(Context ctx) {
inflater = LayoutInflater.from(ctx);
}
public int getCount() {
return contactsList.size();
}
public Object getItem(int position) {
return contactsList.get(position);
}
public long getItemID(int position) {
return position;
}
public VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) {
VIEwHolder holder = null;
if (convertVIEw == null) {
holder = new VIEwHolder();
convertVIEw = inflater.inflate(R.layout.contacts_ListvIEw_item,null);
holder.text1 = (TextVIEw) convertVIEw.findVIEwByID(R.ID.text1);
holder.text2 = (TextVIEw) convertVIEw.findVIEwByID(R.ID.text2);
holder.text3 = (TextVIEw) convertVIEw.findVIEwByID(R.ID.text3);
convertVIEw.setTag(holder);
} else {
holder = (VIEwHolder) convertVIEw.getTag();
}
holder.text1.setText(contactsList.get(position).get("name"));
holder.text2.setText(contactsList.get(position).get("type"));
holder.text3.setText(contactsList.get(position).get("phone"));
return convertVIEw;
}
public final class VIEwHolder {
private TextVIEw text1;
private TextVIEw text2;
private TextVIEw text3;
}
}
}
查询方法语句:
复制代码 代码如下:
/**
* 根据条件查询联系人数据
*
* @param context 上下文环境
* @param keyWord 查询关键字
* @return List<HashMap<String,String>>
*/
public static List<HashMap<String,String>> findContactsByCond(Context context,String keyWord) {
List<HashMap<String,String>>();
sqliteDatabase db = DBHelper.getsqliteDb(context);
String sql = "select * from contacts where name like '" + keyWord + "%' or name_alias like '" + keyWord + "%' order by _ID";
// 查询数据
Cursor cursor = db.rawquery(sql,null);
while (cursor.movetoNext()) {
HashMap<String,String> map = new HashMap<String,String>();
map.put("name",cursor.getString(cursor.getColumnIndex("name")));
map.put("phone",cursor.getString(cursor.getColumnIndex("phone")));
map.put("type",cursor.getString(cursor.getColumnIndex("type")));
map.put("photo",cursor.getString(cursor.getColumnIndex("photo")));
List.add(map);
}
cursor.close();
db.close();
return List;
}
/**
* 存储联系人信息
*
* @param context 上下文环境
* @param contactsList 联系人列表
*/
public static voID saveContacts(Context context,List<HashMap<String,String>> contactsList) {
sqliteDatabase db = DBHelper.getsqliteDb(context);
// 开启事务控制
db.beginTransaction();
try {
// 先将联系人数据清空
db.execsql("drop table if exists contacts");
db.execsql("create table contacts(_ID integer not null primary key autoincrement,name varchar(50),name_alias varchar(10),phone varchar(30),type varchar(50),photo varchar(50))");
String sql = null;
for (HashMap<String,String> contactsMap : contactsList) {
sql = String.format("insert into contacts(name,name_alias,phone,type,photo) values('%s','%s','%s')",contactsMap.get("name"),SaleUtil.getPinYinFirstAlphabet(contactsMap.get("name")),contactsMap.get("phone"),contactsMap.get("type"),contactsMap.get("photo"));
db.execsql(sql);
}
// 设置事务标志为成功
db.setTransactionSuccessful();
} finally {
// 结束事务
db.endTransaction();
db.close();
}
}
工具类:
复制代码 代码如下:
/**
* 判断客户手机号码是否符合规则
*
* @param userPhone 客户手机号码
* @return true | false
*/
public static boolean isValIDPhoneNumber(String userPhone) {
if (null == userPhone || "".equals(userPhone))
return false;
Pattern p = Pattern.compile("^0?1[0-9]{10}");
Matcher m = p.matcher(userPhone);
return m.matches();
}
/**
* 获取中文的拼音首字母
*
* @param chinese 中文
* @return 拼音首字母
*/
public static String getPinYinFirstAlphabet(String chinese) {
String convert = "";
for (int j = 0; j < chinese.length(); j++) {
char word = chinese.charat(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charat(0);
} else {
convert += word;
}
}
return convert;
}
最后加上权限就行了;
复制代码 代码如下:
<!-- 访问联系人的权限 -->
<uses-permission androID:name="androID.permission.READ_CONTACTS" />
总结
以上是内存溢出为你收集整理的android 加载本地联系人实现方法全部内容,希望文章能够帮你解决android 加载本地联系人实现方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)