您的位置:首页 > 其它

HashMap封装查询到的数据

2016-08-25 20:41 288 查看
在读取联系人时,hashmape 封装的是一个人的信息,电话,姓名。

要将联系人全部封装起来需要ArrayList集合。

单个联系人的封装,用键和值的形式将其封装起来。 多个联系人的封装需要集合。

if(cursorData!=null){
HashMap< String, String>map = new HashMap<String,String>();
while(cursorData.moveToNext()){
String  data1=cursorData.getString(0);
String mimetype = cursorData.getString(1);
if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
map.put("phone", data1);
}else if("vnd.android.cursor.item/name".equals(mimetype)){
map.put("name", data1);
}


将hashmape封装起来:

package com.zh.readcontact;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

private ListView lvList;
private ArrayList<HashMap<String, String>> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvList = (ListView) findViewById(R.id.lv_list);
ArrayList<HashMap<String, String>>    conctact=  readContact();

System.out.println(conctact);

}

public ArrayList<HashMap<String, String>>  readContact() {
list = new ArrayList<HashMap<String, String>>();    //创建Arraylist对象,将map封装起来。
ContentResolver resolver = getContentResolver();
// 联系人 中的几张表,
Cursor cursor = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts"),
new String[] { "contact_id" }, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(0);
// System.out.println("联系人id "+contactId);

// 根据得到的contactid 查询data表中的数据; 实际上是从VIew_data中查询到数据。
Cursor cursorData = getContentResolver().query(Uri.parse("content://com.android.contacts/data"),
new String[] { "data1", "mimetype" }, "contact_id=?", new String[] { contactId }, null);
if (cursorData != null) {
HashMap<String, String> map = new HashMap<String, String>();
while (cursorData.moveToNext()) {
String data1 = cursorData.getString(0);
String mimetype = cursorData.getString(1);
if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
map.put("phone", data1);
} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
map.put("name", data1);
}

}
list.add(map);
cursorData.close();

}

}
cursor.close(); // 联系人读取完 把cursor关闭掉。

}
return list;
}
}


listVIew 显示封装的联系人。

SimpleAdapter(Context context, List

lvList = (ListView) findViewById(R.id.lv_list);
ArrayList<HashMap<String, String>>    conctact=  readContact();

lvList.setAdapter(new SimpleAdapter(this, conctact, R.layout.contact_list_item, new String[]{"name","phone"}, new int[]{R.id.tv_name,R.id.tv_phone}));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: