在下一个活动中检索联系人

时间:2012-03-02 18:39:09

标签: android

我从互联网上获得了一个代码,下面的代码是选择联系人并显示它。 我想在下一个ACTIVITY中显示姓名和电话号码:。你可以帮我解决这个问题....

import android.app.Activity;

import android.content.Intent;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.provider.ContactsContract;

import android.widget.TextView;

 public class Contacts_PickerActivity extends Activity

 {

 private TextView tv;

 private static final int CONTACT_PICKER = 1;

 public void onCreate(Bundle savedInstanceState)

 {

 super.onCreate(savedInstanceState);

 tv = new TextView(this);

 setContentView(tv);

 Intent intent = new Intent(Intent.ACTION_PICK,

 ContactsContract.Contacts.CONTENT_URI);

startActivityForResult(intent, CONTACT_PICKER);

}

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

 {

super.onActivityResult(reqCode, resultCode, data);

 switch (reqCode)

 {

case CONTACT_PICKER:

if (resultCode == Activity.RESULT_OK)

 {

 StringBuilder sb = new StringBuilder();

 Uri contactData = data.getData();

 Cursor contactsCursor = managedQuery(contactData, null, null, null, null);

if (contactsCursor.moveToFirst())

 {

String id = contactsCursor.getString(contactsCursor

.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

String name = contactsCursor.getString(contactsCursor

.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

String hasPhoneNumber = contactsCursor.getString(contactsCursor

.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));

sb.append("You picked: " + name + "\n");


if (Integer.parseInt(hasPhoneNumber) > 0) 

{

Uri myPhoneUri = Uri.withAppendedPath(

ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id);

Cursor phoneCursor = managedQuery(

myPhoneUri, null, null, null, null);

for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext())

 {

String phoneNumber = phoneCursor.getString(phoneCursor

.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

sb.append("Phone: " + phoneNumber + "\n");

}

}

 else

{

sb.append("This contact doesn't have a phone number");

}

tv.setText(sb.toString());

}

}

break;

}

}

}

1 个答案:

答案 0 :(得分:1)

在onActivityResult方法中,名称和电话号码作为字符串从Intent数据中提取。您可以将它们作为额外内容传递给您创建的Intent以启动Activity。