我是
Android开发的新手,我正在尝试用名称和电话号码检索联系人列表.我尝试以下代码:
// Get a cursor over every contact. Cursor cursor = getContentResolver().query(People.CONTENT_URI,null,null); // Let the activity manage the cursor lifecycle. startManagingCursor(cursor); // Use the convenience properties to get the index of the columns int nameIdx = cursor.getColumnIndexOrThrow(People.NAME); int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER); String[] result = new String[cursor.getCount()]; if (cursor.movetoFirst()) do { // Extract the name. String name = cursor.getString(nameIdx); // Extract the phone number. String phone = cursor.getString(phoneIdx); result[cursor.getPosition()] = name + "-" +" "+ phone; } while(cursor.movetoNext());
该代码应该返回一个数组,其中包含所有联系人姓名及其电话号码,但这只能返回联系人的姓名,并在电话号码中返回NULL,
示例输出:
John - null
解决方法
在Android清单中:
<uses-permission android:name="android.permission.READ_CONTACTS" />
然后在活动中:
editText.setonFocuschangelistener(new OnFocuschangelistener(){ @Override public void onFocusChange(View v,boolean hasFocus) { if(hasFocus){ editText.setText(""); Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent,PICK_CONTACT); } } });
然后你必须抓住动作选择联系人的结果:
@Override public void onActivityResult(int reqCode,int resultCode,Intent data){ super.onActivityResult(reqCode,resultCode,data); switch(reqCode) { case (PICK_CONTACT): if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData,null); if (c.movetoFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (hasPhone.equalsIgnoreCase("1")) { Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null); phones.movetoFirst(); String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Toast.makeText(getApplicationContext(),cNumber,Toast.LENGTH_SHORT).show(); String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.disPLAY_NAME)); editText.setText(nameContact+ " "+ cNumber); } } } } }