从联系人选择器中获取号码
Posted
技术标签:
【中文标题】从联系人选择器中获取号码【英文标题】:Getting Number from Contacts Picker 【发布时间】:2011-09-03 13:53:49 【问题描述】:在用户从联系人选择器中选择联系人后,我试图获取联系人姓名和电话号码。我试图让我的应用程序适用于 SDK v3 及更高版本,因此我创建了一个抽象类,它只调用我需要的 API。我已经让抽象类工作了(它选择了正确的 API),并且我还有用于 SDK v3,4 的 API 工作。我在获取使用 ContactsContract 的新 API 时遇到问题。
我可以获取联系人姓名,但它检索到的号码始终是它之前的联系人 ID 的号码!示例:我有 2 个联系人“John Doe”和“Jane Doe”,分别在联系人中添加了“555-555-555”和“777-777-7777”号码。 John Doe 的 ID=1,Jane Doe 的 ID=2。如果我尝试获取 Jane Doe 的电话号码,我会得到 John 的电话,555-555-5555。如果我试图得到约翰的,我什么也得不到。 if (cursor.moveToNext()) 的检查失败。
你能帮我解决这个问题吗?这让我快疯了。我看了很多例子,总是得到同样的错误。
Intent 数据是来自 onActivityResult 的数据 Intent
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
class NewContactsAdapterBridge extends ContactsAdapterBridge
ArrayList<String> info = new ArrayList<String>();
ArrayList<String> getInfo (Activity a, Intent data)
Uri contactData = data.getData();
Cursor cursor = a.managedQuery(contactData, null, null, null, null);
if (cursor.moveToFirst())
String id = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow
(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
info.add(name);
if (Integer.parseInt(hasPhoneNumber) > 0)
Uri myPhoneUri = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
id);
Cursor pCur = a.managedQuery(
myPhoneUri,
null,
null,
null,
null);
if (pCur.moveToNext())
String number = pCur.getString( pCur.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
info.add(number);
return info;
【问题讨论】:
【参考方案1】:@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode == RESULT_OK)
switch (requestCode)
case CONTACT_PICKER_RESULT:
final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
Cursor cursor = null;
String phoneNumber = "";
List<String> allNumbers = new ArrayList<String>();
int phoneIdx = 0;
try
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] id , null);
phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst())
while (cursor.isAfterLast() == false)
phoneNumber = cursor.getString(phoneIdx);
allNumbers.add(phoneNumber);
cursor.moveToNext();
else
//no results actions
catch (Exception e)
//error actions
finally
if (cursor != null)
cursor.close();
final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
builder.setTitle("Choose a number");
builder.setItems(items, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int item)
String selectedNumber = items[item].toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
);
AlertDialog alert = builder.create();
if(allNumbers.size() > 1)
alert.show();
else
String selectedNumber = phoneNumber.toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
if (phoneNumber.length() == 0)
//no numbers found actions
break;
else
//activity result error actions
您需要对其进行调整以与您的应用一起使用
【讨论】:
非常感谢。您的代码与我发现的任何其他代码都不同,而且效果很好。此外,您选择哪个号码的代码非常有用。 像魅力一样工作。我忘记添加 READ_CONTACTS 权限,因此一开始没有工作,但后来我发现选择联系人是最好的。谢谢。 :) 什么是 CONTACT_PICKER_RESULT?我做不到。 我必须把这个findViewById(R.id.phoneNumberInput)
视图放在 xml @Ciprian Radu 中的什么地方【参考方案2】:
我想得到那一行案例 CONTACT_PICKER_RESULT...我上面使用的代码使用这个
int PICK_CONTACT;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.button1);
et=(EditText) findViewById(R.id.editText1);
b.setOnClickListener(this);
//et.setOnClickListener(this);
@Override
public void onClick(View v)
switch(v.getId())
case R.id.button1:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
// case R.id.editText1:
// break;
【讨论】:
【参考方案3】: Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
这些代码对你有帮助,我认为 PICK 活动只返回所选联系人的 ID。从中您可以查询联系人提供商,如果有多个电话号码,则提示用户选择其中一个。
你也可以用这个
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode == RESULT_OK)
switch (requestCode)
case CONTACT_PICKER_RESULT:
final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
Cursor cursor = null;
String phoneNumber = "";
List<String> allNumbers = new ArrayList<String>();
int phoneIdx = 0;
try
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] id , null);
phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst())
while (cursor.isAfterLast() == false)
phoneNumber = cursor.getString(phoneIdx);
allNumbers.add(phoneNumber);
cursor.moveToNext();
else
//no results actions
catch (Exception e)
//error actions
finally
if (cursor != null)
cursor.close();
final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
builder.setTitle("Choose a number");
builder.setItems(items, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int item)
String selectedNumber = items[item].toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
);
AlertDialog alert = builder.create();
if(allNumbers.size() > 1)
alert.show();
else
String selectedNumber = phoneNumber.toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
if (phoneNumber.length() == 0)
//no numbers found actions
break;
else
//activity result error actions
【讨论】:
我要把这个findViewById(R.id.phoneNumberInput)
@Sathish放在哪里
在 onCreate() 方法中可以使用的任何地方。【参考方案4】:
初学者请注意,不要忘记包含以下权限,否则它将不起作用
<uses-permission android:name="android.permission.READ_CONTACTS"/>
【讨论】:
【参考方案5】: switch (reqCode)
case (REQUEST_CODE_email):
if (resultCode == Activity.RESULT_OK)
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst())
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String num = "";
if (Integer.valueOf(hasNumber) == 1)
Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext())
num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
//asdasdasdsa
if(getEmail(num).isEmpty())
Toast.makeText(this, "Email Not Found In That Contact Try Another", Toast.LENGTH_SHORT).show();
else
edt_email_contact.setText("" + getEmail(num));
break;
case (REQUEST_CODE_number):
if (resultCode == Activity.RESULT_OK)
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst())
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String num = "";
if (Integer.valueOf(hasNumber) == 1)
Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext())
num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
//asdasdasdsa
edt_email_contact.setText("" + num);
break;
【讨论】:
以上是关于从联系人选择器中获取号码的主要内容,如果未能解决你的问题,请参考以下文章