Android SDK 2.0以上读取手机联系人

2014-11-24 08:54:31 ? 作者: ? 浏览: 0

具体读取联系人及号码,以ListView方式显示,代码如下。


public class ReadContacts extends Activity {


ListView listView;


ListAdapter adapter;


@Override


public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);


LinearLayout linearLayout = new LinearLayout(this);


linearLayout.setOrientation(LinearLayout.VERTICAL);


linearLayout.setBackgroundColor(Color.BLACK);


LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(


LinearLayout.LayoutParams.FILL_PARENT,


LinearLayout.LayoutParams.WRAP_CONTENT);



listView = new ListView(this);


listView.setBackgroundColor(Color.BLACK);


linearLayout.addView(listView, param);


this.setContentView(linearLayout);



// 生成动态数组,加入数据


ArrayList> listItem = new ArrayList>();


ArrayList> listItemRead= newArrayList>();


Cursor cursor = getContentResolver().query(


ContactsContract.Contacts.CONTENT_URI, null, null, null, null);


while(cursor.moveToNext()) {


HashMap map = new HashMap();


String phoneName = cursor.getString(cursor


.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


map.put("ItemTitle", phoneName);// 电话姓名


String contactId = cursor.getString(cursor


.getColumnIndex(ContactsContract.Contacts._ID));


String hasPhone = cursor


.getString(cursor


.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));



if(hasPhone.compareTo("1") == 0) {


Cursor phones = getContentResolver().query(


ContactsContract.CommonDataKinds.Phone.CONTENT_URI,


null,


ContactsContract.CommonDataKinds.Phone.CONTACT_ID


+ " = " + contactId, null, null);


while(phones.moveToNext()) {


String phoneNumber = phones


.getString(phones


.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


String phoneTpye = phones


.getString(phones


.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));


map.put("ItemText", phoneNumber); // 多个号码如何处理


}


phones.close();


}


listItem.add(map);


}



// 生成适配器的Item和动态数组对应的元素


SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源


android.R.layout.simple_list_item_2,// ListItemXML实现


// 动态数组与ImageItem对应的子项


new String[] { "ItemTitle", "ItemText" },


new int[] { android.R.id.text1, android.R.id.text2 });


listView.setAdapter(listItemAdapter);


cursor.close();


}



}


-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: