简体   繁体   中英

Android Contact Phone, Address and Name Intent

I'm using a basic Intent to grab a contact in Android Studio. Once a contact is selected, I want to extract address (home), phone and name. I'm currently only able to get name/address or name/phone. I'm not able to get all 3 because of the intent type I believe.

The issue begins in addDeliveryItem() with the intent. Depending on the intent type, I can pull phone number or address. I need both!!!

Something curious I noticed: My getContactIDFromURI() returns a different contact ID depending on the intent type.

I have made a big edit to this post in hopes that I can find an answer. I have now included the entire .java file in case you can spot any problems. I'm going crazy and would send some serious love to whoever can figure this one out :(.

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    //our main super list of deliveries
    ArrayList<String> deliveryListItems = new ArrayList<String>();

    //string adaptor that will handle data of listview
    MyCustomAdapter adapter;

    //clickCount
    int clickCounter = 0;

    //this is required to pick a contact for some reason.
    private static int PICK_CONTACT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize our custom adapter for custom list
        adapter = new MyCustomAdapter(deliveryListItems, this);

        ListView lView = (ListView)findViewById(android.R.id.list);
        lView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /* Begin custom Deliverance functions */
    public void addDeliveryItem(View v){
        //these 3-4 lines create an intent to pick contacts. INTENT TYPE IS DRIVING ME CRAZY
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        //intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE);
        startActivityForResult(intent, PICK_CONTACT);
    }

    //this function handles receiving contact numbers after they have been picked with intent
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //URI to store the contact URI - basically URL to contact
        Uri uriContact;
        String contactName = null;
        String contactPhone = null;
        String contactAddress = null;
        String contactID = null;

        //successful contact lookup like a boss
        if ((requestCode == PICK_CONTACT) && (resultCode == RESULT_OK)) {
            //store contact URI
            uriContact = data.getData();

            contactName = getContactNameFromURI(uriContact);
            contactPhone = getContactPhoneFromURI(uriContact);
            contactID = getContactIdFromURI(uriContact);
            contactAddress = getContactAddressFromURI(uriContact);

            //add result to list
            deliveryListItems.add(contactName);
            deliveryListItems.add(contactPhone);
            deliveryListItems.add(contactAddress);
            deliveryListItems.add(contactID);

            adapter.notifyDataSetChanged();
            clickCounter++;
        }
    }

    public String getContactIdFromURI(Uri uri){
        String contactID = null;

        // getting contacts "ID" that we need for stuff
        Cursor cursorID = getContentResolver().query(uri,
                new String[]{ContactsContract.Contacts._ID},
                null, null, null);

        if (cursorID.moveToFirst()) {
            contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
        }
        cursorID.close();

        return contactID;
    }

    public String getContactNameFromURI(Uri uri){
        String contactName = null;
        // querying contact data store
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor.moveToFirst()) {
            // DISPLAY_NAME = The display name for the contact.
            // HAS_PHONE_NUMBER =   An indicator of whether this contact has at least one phone number.
            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

        cursor.close();
        return contactName;
    }

    public String getContactPhoneFromURI(Uri uri){
        String contactNumber = null;
        String contactID = getContactIdFromURI(uri);

        // Using the contact ID now we will get contact phone number
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{contactID},
                null);

        if (cursor.moveToFirst()) {
            contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }

        cursor.close();
        return contactNumber;
    }

    public String getContactAddressFromURI(Uri uri){
        String rAddress = null;
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor.moveToFirst()) {
            try {
                rAddress = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
            }catch(Exception e){
                return "nope";
            }
        }

        cursor.close();
        return rAddress;
    }
}

Can I set the intent type to be able to retrieve all the data I need? I obviously don't want to have to select the contact again.

I'm very sorry if this is a simple question. I'm still new with Android development :).

Edit: here are my functions for retrieving contact phone, name and address given URI. They all work with different intent types.

As mentioned by @Shaik you can try this to get a Contact ID

public static int getContactIDFromNumber(String contactNumber,Context context)
{
    contactNumber = Uri.encode(contactNumber);
    int phoneContactID = new Random().nextInt();
    Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.contactNumber),new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
        while(contactLookupCursor.moveToNext()){
            phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
            }
        contactLookupCursor.close();

    return phoneContactID;
}

In order to get Contact name,id,photo,phone you can refer this Gist . It gives you a clear explanation. For getting the address of the contact you have to modify the code in the Gist and add a new function, which is something like given below.

// get the contact ID

Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
cursor.moveToFirst();
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();

// get the data package containg the postal information for the contact
cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, 
    new String[]{ StructuredPostal.STREET,
        StructuredPostal.CITY,
// add more coluns from StructuredPostal if you need them
        StructuredPostal.POSTCODE},
        ContactsContract.Data.CONTACT_ID + "=? AND " +
            StructuredPostal.MIMETYPE + "=?",
        new String[]{String.valueOf(id), StructuredPostal.CONTENT_ITEM_TYPE},
        null);


Street = cursor.getString(cursor.getColumnIndex(StructuredPostal.STREET));
Postcode = cursor.getString(cursor.getColumnIndex(StructuredPostal.POSTCODE));
City = cursor.getString(cursor.getColumnIndex(StructuredPostal.CITY)));
// etc. 

This worked for me. You can try it and let me know if you have some troubles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM