android 中从数据库中读取联系人,并用listview展示出来;
public class ContactsActivity extends Activity {
// ListView 存储数据
ListView contactsView;
// ArrayAdapter 绑定的数据类型,可以是基本数据类型,也可以是自定义的对象类型
ArrayAdapter<String> adapter;
List<String> contactsList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
contactsView = (ListView) findViewById(R.id.contacts_view);
// 设置adapter
// android.R.layout.simple_list_item_1 系统定义的布局文件只显示一行文字
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactsList);
contactsView.setAdapter(adapter);
readContacts();
}
public void readContacts() {
Cursor cursor = null;
try {
// 从数据库查询联系人
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// 采用遍历的方式
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName + "\n" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(cursor != null) {
cursor.close();
}
}
}
}
联系人布局文件(部分)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/contacts_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
AndroidManifest.xml中配置读取联系人权限
<uses-permission android:name="android.permission.READ_CONTACTS" />