android之獲取聯絡人列表
阿新 • • 發佈:2018-12-30
public class SelectContactActivty extends Activity { private ListView lt_selectcontact; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_selectcontact); lt_selectcontact = findViewById(R.id.lt_selectcontact); final List<Map<String, String>> data = getContactInfo();//獲取使用者列表 // Adapter adp=new SimpleAdapter(this,data,R.layout.contact_item,new String[]{"name","phone"},new int[]{R.id.tv_contatc_name,R.id.tv_contatc_phonenum}); // lt_selectcontact.setAdapter((ListAdapter) adp); lt_selectcontact.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { String phone=data.get(i).get("phone"); Intent data=new Intent(); data.putExtra("phone",phone); setResult(0,data); finish(); } }); } //讀取手機裡面的聯絡人 public List<Map<String, String>> getContactInfo() { //吧所有聯絡人填進去 List<Map<String, String>> list = new ArrayList<Map<String, String>>(); ContentResolver resolver = getContentResolver(); String uristring = "content://com.android.contacts/raw_contacts"; String data = "content://com.android.contacts/raw_contacts/data"; Uri uri = Uri.parse(uristring); Uri uridata = Uri.parse(data); Cursor cursor = resolver.query(uri, new String[]{"contact_id"}, null, null, null); while (cursor.moveToNext()) { String contact_id = cursor.getString(0); if (contact_id != null) { //具體的某一個聯絡人 Map<String, String> map = new HashMap<String, String>(); Cursor datacursor = resolver.query(uridata, new String[]{"data1", "mimetype"}, "contact_id=?", new String[]{contact_id}, null); while (datacursor.moveToNext()) { String data1 = datacursor.getString(0); String mimetype = datacursor.getString(1); if ("vnd.android.cursor.item/name".equals(mimetype)) { //聯絡人的姓名 map.put("name", data1); } else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) { //聯絡人的電話號碼 map.put("phone", data1); } } list.add(map); datacursor.close(); } } return list; } }
<?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/tv_nav" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="22sp" android:text="選擇聯絡人" android:gravity="center" android:background="#8866ff00"/> <ListView android:id="@+id/lt_selectcontact" android:layout_width="match_parent" android:layout_height="match_parent" ></ListView> </LinearLayout>