在上一篇学习ListView的时候,看到在API中获取联系人的例子已经不被官方推荐了。于是,手痒又查了查,看看使用Android如何获取联系人信息。这篇可以说着对ListView继续深入学习,也是对android中访问联系人信息的学习。
在学习的过程中参考了很多资料,其中写得比较好的是这一篇http://xys289187120.blog.51cto.com/3361352/656766
我的例子也基本上是模仿他写的。
下面看代码
package com.example.contactlist;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
Context myContext = null;
MyListAdapter myListAdapter = null;
TextView name = null;
TextView number = null;
//这两个List用于暂时存储联系人的名字和号码
List<String> myContactName = new ArrayList<String>();
List<String> myContactNumber = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
myContext = this;
//使用getContentResolver方法来读取联系人的表
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while(cursor.moveToNext()){
//联系人的ID
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//联系人的名称
String name