如何将点击的联系人列表项号码传递至另一个Activity?——短信App开发中的Intent传值障碍
Hey there! Let's work through this issue together. It sounds like you've got your contact list pulling data correctly, but you're stuck on passing the selected phone number to your messaging Activity. The core problem here is that your current code only logs contact details—you need to store that data first, then bind it to your list so you can access it when a user taps a contact.
Here's how to fix this step by step:
1. Create a Contact Model Class
First, make a simple class to hold each contact's name and phone number. This makes it easy to manage and access the data later:
public class Contact { private String name; private String phoneNumber; public Contact(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } public String getName() { return name; } public String getPhoneNumber() { return phoneNumber; } }
2. Update Your Contact Fetching Code
Modify your getContactList() method to store contacts in a list, then bind that list to your UI (we'll use a ListView as an example):
private List<Contact> contactList = new ArrayList<>(); private void getContactList() { ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if ((cur != null ? cur.getCount() : 0) > 0) { while (cur != null && cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); // Note: If a contact has multiple numbers, this takes the first one—adjust if needed if (pCur.moveToNext()) { String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); contactList.add(new Contact(name, phoneNo)); // Store the contact Log.i(TAG, "Name: " + name); Log.i(TAG, "Phone Number: " + phoneNo); } pCur.close(); } } } if (cur != null) cur.close(); // Bind the list to your ListView ArrayAdapter<Contact> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_2, android.R.id.text1, contactList) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView nameTxt = view.findViewById(android.R.id.text1); TextView phoneTxt = view.findViewById(android.R.id.text2); Contact contact = contactList.get(position); nameTxt.setText(contact.getName()); phoneTxt.setText(contact.getPhoneNumber()); return view; } }; ListView contactListView = findViewById(R.id.your_listview_id); // Replace with your ListView's ID contactListView.setAdapter(adapter); // Add click listener to pass data to messaging Activity contactListView.setOnItemClickListener((parent, view, position, id) -> { Contact selectedContact = contactList.get(position); String targetPhone = selectedContact.getPhoneNumber(); // Create intent and pass the phone number Intent smsIntent = new Intent(this, YourMessagingActivity.class); smsIntent.putExtra("SELECTED_PHONE_NUMBER", targetPhone); startActivity(smsIntent); }); }
3. Receive the Phone Number in Your Messaging Activity
In the Activity where you want to send the SMS, retrieve the phone number from the Intent:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_messaging); // Get the passed phone number String phoneNumber = getIntent().getStringExtra("SELECTED_PHONE_NUMBER"); if (phoneNumber != null) { // Use the number—e.g., populate an input field or directly prepare an SMS EditText phoneInput = findViewById(R.id.sms_phone_input); phoneInput.setText(phoneNumber); } }
4. Critical: Permissions Setup
Don't forget to add the required permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.SEND_SMS" />
And handle dynamic permission requests (required for Android 6.0+):
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_list); // Check for contacts permission before fetching data if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 100); } else { getContactList(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 100) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getContactList(); } else { Toast.makeText(this, "Contacts permission is required to use this feature", Toast.LENGTH_SHORT).show(); } } }
The key issue you were facing was not storing the contact data in a accessible format—once you have the contacts in a list, accessing the phone number on click and passing it via Intent.putExtra() works exactly like any other list item transfer.
内容的提问来源于stack exchange,提问作者Utaiba Naqshbandi

