Search code examples
javaandroidandroid-intentonitemclicklistener

How To Pass Clicked List Item Value to another Activity?


I'm making a SMS app, I have a contact list, I want to be able to tap on contact and pass that contact number into new activity so that I could send message to that contact number, I know How can we pass Value of clicked List item to new Activity, but somehow I'm not able to use that Intent.putExtra method in my scenario.

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);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if (cur != null) {
        cur.close();
    }
}

Solution

  • You can use a Bundle to do this. You mentioned that you somehow couldn't call putExtra on your intent, make sure it isn't a typo as it is supposed to be putExtras, also make sure you are creating your intent correctly as shown below.

    In the activity that will send the data:

    Intent intent = new Intent(getActivity(), SecondActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("phoneNo", phoneNo);
    intent.putExtras(bundle);
    startActivity(intent);
    

    Then on the receiving activity:

    Bundle bundle = getIntent().getExtras();
    String number = bundle.getString("phoneNo");