简体   繁体   English

Android联系人电话,地址和名称意图

[英]Android Contact Phone, Address and Name Intent

I'm using a basic Intent to grab a contact in Android Studio. 我正在使用基本的Intent来在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. 由于我相信的意图类型,我无法获得全部3个。

The issue begins in addDeliveryItem() with the intent. 该问题始于具有意图的addDeliveryItem()。 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. 我注意到了一些奇怪的事情:我的getContactIDFromURI()返回一个不同的联系人ID,具体取决于意图类型。

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. 现在,我包括了整个.java文件,以防您发现任何问题。 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 :). 我还是Android开发的新手:)。

Edit: here are my functions for retrieving contact phone, name and address given URI. 编辑:这是我获取联系人电话,给定URI的名称和地址的功能。 They all work with different intent types. 它们都以不同的意图类型工作。

As mentioned by @Shaik you can try this to get a Contact ID 如@Shaik所述,您可以尝试获取联系人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. 为了获得联系人的地址,您必须在Gist中修改代码并添加一个新功能,如下所示。

// 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. 您可以尝试一下,如果遇到麻烦,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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