读取联系人信息

本文介绍了如何在Android平台上读取设备中的联系人信息,包括获取联系人列表、详细信息以及使用权限管理的相关步骤。
摘要由CSDN通过智能技术生成

读取联系人信息

这里写图片描述

public class MainActivity extends AppCompatActivity {
    private List<Person> personList = new ArrayList<>();
    private MyAdapt myAdapt;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listview);
        myAdapt = new MyAdapt();
        listView.setAdapter(myAdapt);
        readContacts();
    }

    class Person{
        String name;
        String tel;

        public Person(String name, String tel) {
            this.name = name;
            this.tel = tel;
        }
    }
    // 读取联系人
    public void readContacts() {
        // 获取内容解析者的游标
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                // 获取联系人姓名
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                // 获取联系人电话号码
                String tel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Person person = new Person(name, tel);
                personList.add(person);
            }
        }
        cursor.close();
        myAdapt.notifyDataSetChanged();
    }

    class MyAdapt extends BaseAdapter{

        @Override
        public int getCount() {
            return personList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = getLayoutInflater().inflate(R.layout.item, null, false);
            TextView tvName = (TextView) itemView.findViewById(R.id.tv_name);
            TextView tvTel = (TextView) itemView.findViewById(R.id.tv_tel);
            tvName.setText(personList.get(position).name);
            tvTel.setText(personList.get(position).tel);
            return itemView;
        }
    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值