嗨,我正在开发一个向所选联系人发送短信的应用程序。
选择我正在使用此代码的联系人
public void selectRecipient(View V)
{
Intent pickContactIntent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(pickContactIntent,1);
}
我的onActivityResult功能正在关注
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
if(requestCode==1)
{
count++;
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
name= c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = c.getString(c.getColumnIndex(Contacts._ID));
Cursor cur =getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
cur.moveToNext();
String phoneNumber = cur.getString(cur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
}
}
当我在联系人列表中选择任何谷歌联系人时,我会强行关闭。
如果我选择了具有数字的手机联系人,那么它的工作正常。
我该怎么做才能纠正这个问题?
答案 0 :(得分:1)
您需要检查当前联系人是否至少有一个电话号码使用ContactsContract.Contacts.HAS_PHONE_NUMBER
并使用Cursor
关闭Cursor.close();
获取电话号码后。因此,请将您的代码更改为:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case (1) :
{
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String phoneNumber=this.getContactPhone(c);
}
break;
}
}
}
private String getContactPhone(Cursor cursor)
{
int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
int phoneNum = cursor.getInt(phoneColumn);
String phoneResult="";
//System.out.print(phoneNum);
if (phoneNum > 0)
{
int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactId = cursor.getString(idColumn);
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = " + contactId,
null, null);
//int phoneCount = phones.getCount();
//allPhoneNum = new ArrayList<String>(phoneCount);
if (phones.moveToFirst())
{
for (;!phones.isAfterLast();phones.moveToNext())
{
int index = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int typeindex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int phone_type = phones.getInt(typeindex);
String phoneNumber = phones.getString(index);
switch(phone_type)
{
case 2:
phoneResult=phoneNumber;
break;
}
//allPhoneNum.add(phoneNumber);
}
if (!phones.isClosed())
{
phones.close();
}
}
}
return phoneResult;
}
<小时/> 并且确保您在AndroidManifest.xml中拥有以下权限。
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />