How to extract phone number from the selected cont

2019-09-18 10:26发布

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;
    }
}

I am developing an Android apps and I am importing the phone contacts into my apps, after user clicks on the selected contact, the contact will be shown in a TextView and the phone number will be stored in the sharedpreferences... May I know how to achieve it? Thanks

2条回答
叛逆
2楼-- · 2019-09-18 11:13

Have you tried?

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);

For store in 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();

The above code is just for understanding..

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-18 11:13

A possible duplicate of the following link

get contact info from android contact picker

Refer to the above link. It has been answered in detail.

查看更多
登录 后发表回答