内容提供者,SimpleAdapter
1 public class MainActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 ListView listView = (ListView) findViewById(R.id.lv); 9 10 ArrayList<HashMap<String, String>> readContact = readContact(); 11 12 listView.setAdapter(new SimpleAdapter(this,readContact,R.layout.item_layout, 13 new String[] {"name","number"},new int[]{R.id.tv_name,R.id.tv_number})); 14 } 15 16 private ArrayList<HashMap<String, String>> readContact() { 17 18 ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); 19 20 //查询联系人数据 21 Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 22 null,null,null,null); 23 //遍历联系人 24 while (cursor.moveToNext()) { 25 HashMap<String, String> map = new HashMap<String, String>(); 26 //获取联系人姓名 27 String displayName = cursor.getString( 28 cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 29 map.put("name",displayName); 30 //获取联系人手机号 31 String number = cursor.getString( 32 cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 33 map.put("number",number); 34 Log.e("test","姓名:" + displayName + "手机号:" + number); //将map添加到list集合 35 list.add(map); 36 } 37 38 cursor.close(); 39 40 return list; 41 } 42 }
时间: 2024-10-22 12:02:35