原文:
在《Android应用开发揭秘》4.2.2ListView一节中 读取联系人显示在ListView的实例
源码如下:
Java代码
- package android.app.contacts;
- import android.app.Activity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.provider.ContactsContract.PhoneLookup;
- import android.widget.LinearLayout;
- import android.widget.ListAdapter;
- import android.widget.ListView;
- import android.widget.SimpleCursorAdapter;
- public class ContactsActivity extends Activity {
- LinearLayout linearlayout;
- ListView listview;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- linearlayout = new LinearLayout(this);
- linearlayout.setOrientation(LinearLayout.VERTICAL);
- linearlayout.setBackgroundColor(android.graphics.Color.GRAY);
- listview = new ListView(this);
- LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.FILL_PARENT,
- LinearLayout.LayoutParams.WRAP_CONTENT);
- listview.setBackgroundColor(android.graphics.Color.BLACK);
- linearlayout.addView(listview, params);
- setContentView(linearlayout);
- Cursor cur = getContentResolver().query(
- ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
- startManagingCursor(cur);
- ListAdapter adapter = new SimpleCursorAdapter(this,
- android.R.layout.simple_list_item_2, cur, new String[] {
- PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER },
- new int[] { android.R.id.text1, android.R.id.text2 });
- listview.setAdapter(adapter);
- }
- }
发生错误!!!
原因:
ContactsContract.Contacts.CONTENT_URI
PhoneLookupp.NUMBER
在Android2.0以上平台已失效
改成以下语句即可:
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
CntactsContract.CommonDataKinds.Phone.NUMBER