如何从所选联系人中提取电话号码?

时间:2012-05-17 10:53:06

标签: java android android-contacts

public class ImportContactsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button pickContact = (Button) findViewById(R.id.contacts);
    pickContact.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, 1);
        }
    });
}

public void onActivityResult(int reqCode, int resultCode, Intent data) {

    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
    case (1) :
      if (resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        Cursor c =  managedQuery(contactData, null, null, null, null);

        if (c.moveToFirst()) {
          String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
          TextView contactView = (TextView) findViewById(R.id.contactView);
          contactView.setText(name.toString());
        }
      }
      break;
    }
}

我正在开发Android应用程序,我正在将手机通讯录导入我的应用程序,用户点击所选联系人后,该联系人将显示在TextView中,并且电话号码将存储在共享偏好中...我知道如何实现它?感谢

2 个答案:

答案 0 :(得分:1)

你试过吗?

Uri contactData = data.getData();
Cursor cursor =  managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
      String name = cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
      String number = cursor.getString(cursor.getColumnIndexOrThrow(People.NUMBER));
      String email = cursor.getString(cursor.getColumnIndexOrThrow(People.PRIMARY_EMAIL_ID));
      contactName.setText(name);
      contactNumber.setText(number);
      contactEmail.setText(email);

对于SharedPreferences中的商店..

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("phonenumber", number);

  // Commit the edits!
  editor.commit();

以上代码仅供理解..

答案 1 :(得分:0)

以下链接的可能重复

get contact info from android contact picker

请参阅以上链接。已经详细解答了。