读取联系人信息

来源:互联网 发布:windows资源管理器 编辑:程序博客网 时间:2024/05/22 06:08

读取联系人信息

这里写图片描述

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;        }    }}

这里写图片描述

0 0