codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

Edit name/phone number of contact programmatically


By : , Category : android

You should specify the mimetype in your selection.

.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
               Data.MIMETYPE + "='" +
               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
               new String[]{contact_id})

If you haven't figured this out yet, give that a go. I found updating contacts to be very tricky in getting the selection arguments right.

ReLated :

Try the Windows.ApplicationModel.Contacts namespace

Note: the Windows.ApplicationModel.Contacts namespace is only supported by WP8.1

Here is a code snippet for creating the contact:

 public async Task AddContact(String FirstName, String LastName)
  {
    var contact = new Windows.ApplicationModel.Contacts.Contact();
    contact.FirstName = FirstName;
    contact.LastName = LastName;
    //Here you can set other properties...

    //Get he contact store for the app (so no lists from outlook and other stuff will be in the returned lists..)
    var contactstore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);

    try
    {
        var contactLists = await contactstore.FindContactListsAsync();

        Windows.ApplicationModel.Contacts.ContactList contactList;

        //if there is no contact list we create one
        if (contactLists.Count == 0)
        {
            contactList = await contactstore.CreateContactListAsync("MyList");
        }
        //otherwise if there is one then we reuse it
        else
        {
            contactList = contactLists.FirstOrDefault();
        }

        await contactList.SaveContactAsync(contact);
    }
    catch
    {
        //Handle it properly... 
    }
}

And here is a short sample for changing an existing contact:

//you can obviusly couple the changes better then this... this is just to show the basics 
public async Task ChangeContact(Windows.ApplicationModel.Contacts.Contact ContactToChange, String NewFirstName, String NewLastName)
{
    var contactStore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);

    var contactList = await contactStore.GetContactListAsync(ContactToChange.ContactListId);

    var contact = await contactList.GetContactAsync(ContactToChange.Id);

    contact.FirstName = NewFirstName;
    contact.LastName = NewLastName;

    await contactList.SaveContactAsync(contact);
}

And very important: In the appxmanifest you have to add the contacts capability. Right click to it in the solution explorer and "View Code" and then under Capabilities put

<uap:Capability Name="contacts" />

There is no UI for this. See this.

Both samples are meant to be for starting point... obviously it's not production ready and you have to adapt it to your scenario.

Update

Since this came up in the comments I extend my answer a little bit.

Based on this (plus my own experimentation) the ContactListId for aggregated contacts is null (which makes sense if you think about it). Here is how to get the raw contact with ContactlLstId (code is based on the comment from the link)

 public async Task IterateThroughContactsForContactListId()
 {            
            ContactStore allAccessStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);

            var contacts = await allAccessStore.FindContactsAsync();
            foreach (var contact in contacts)
            {
                //process aggregated contacts
                if (contact.IsAggregate)
                {
                    //here contact.ContactListId is "" (null....)                  
                    //in this case if you need the the ContactListId then you need to iterate through the raw contacts
                    var rawContacts = await allAccessStore.AggregateContactManager.FindRawContactsAsync(contact);
                    foreach (var rawContact in rawContacts)
                    {
                        //Here you should have ContactListId
                        Debug.WriteLine($"aggregated, name: {rawContact.DisplayName }, ContactListId: {rawContact.ContactListId}");
                    }
                }
                else //not aggregated contacts should work
                {
                    Debug.WriteLine($"not aggregated, name: {contact.DisplayName }, ContactListId: {contact.ContactListId}");
                }
            }

}

And another important thing:

According to the documentation you won’t be able to change all the contacts which are created by other apps.

AllContactsReadWrite:

Read and write access to all app and system contacts. This value is not available to all apps. Your developer account must be specially provisioned by Microsoft in order to request this level of access.

In some cases, I get a System.UnauthorizedAccessException when SaveContactAsync(contact) is called. One example for this was when the contact was in the Skype Contact List.

I got your example working by adding a CustomAdapter MyClassAdapter which extends ArrayAdapter, and populating an ArrayList of Contact objects.

import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class Provider2Activity extends ListActivity {

    ArrayList<Contact> contacts;

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

        contacts = new ArrayList<Contact>();

        Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

        //declare our cursor
        Cursor c;

        String[] projection = new String[]
                {ContactsContract.Contacts._ID,
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.Contacts.HAS_PHONE_NUMBER};


        /* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
            controls how many columns are returned by the query; this parameter is known as the projection
           >>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
           enable you to specify a SQL WHERE clause to filter the result of the query
           >>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
           enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
        * */
        if (android.os.Build.VERSION.SDK_INT <11) {
            //---if the device ids running on OS before Honeycomb
            //use the managedQuery() of the Activity class to retrieve a managed cursor
            c = managedQuery(allContacts, projection, null, null, null);

        }
        else {
            //---Honeycomb and later use the cursor loader class to retrieve managed cursor---
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    projection,
                    null,
                    null ,
                    null);
            c = cursorLoader.loadInBackground();
        }

        PrintContacts(c);

        MyClassAdapter adapter;


        //detect the android version again..
        if (android.os.Build.VERSION.SDK_INT <11) {
            //---if it is before Honeycomb---

            adapter = new MyClassAdapter(
                    this, R.layout.row_line, contacts);
        }
        else {
            //---Honeycomb and later---

            adapter = new MyClassAdapter(
                    this, R.layout.row_line, contacts);
        }

        this.setListAdapter(adapter);

    }

    private void PrintContacts(Cursor c)
    {
        ContentResolver cr = getContentResolver();
        //---display the contact id and name and phone number----
        if (c.moveToFirst()) {
            do{
                //---get the contact id and name
                String contactID = c.getString(c.getColumnIndex(
                        ContactsContract.Contacts._ID));
                String contactDisplayName =
                        c.getString(c.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME));
                Log.v("Content Providers", contactID + ", " +
                        contactDisplayName);

                String contactDisplayPhone = "";
                    //---get phone number---
                int hasPhone =
                        c.getInt(c.getColumnIndex(
                                ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if (hasPhone == 1) {
                    Cursor phoneCursor =
                            getContentResolver().query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
                                            contactID, null, null);
                    while (phoneCursor.moveToNext()) {
                        Log.v("Content Providers",
                                contactDisplayPhone = phoneCursor.getString(
                                        phoneCursor.getColumnIndex(
                                                ContactsContract.CommonDataKinds.Phone.NUMBER)));
                    }
                    phoneCursor.close();

                }
                contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));

            } while (c.moveToNext());
        }
    }

    public class Contact{
        public String contactName = "";
        public String contactID = "";
        public String contactNumber = "";
        public Contact(String name, String id, String number){

            contactName = name;
            contactID = id;
            contactNumber = number;
        }
    }

    public class MyClassAdapter extends ArrayAdapter<Contact> {

        private class ViewHolder {
            private TextView name;
            private TextView id;
            private TextView number;
        }

        public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
            super(context, textViewResourceId, items);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(this.getContext())
                        .inflate(R.layout.row_line, parent, false);

                viewHolder = new ViewHolder();
                viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
                viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
                viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            Contact item = getItem(position);
            if (item!= null) {
                viewHolder.name.setText(item.contactName);
                viewHolder.id.setText(item.contactID);
                viewHolder.number.setText(item.contactNumber);
            }

            return convertView;
        }
    }

}

row_line.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView android:id="@+id/contactName"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView android:id="@+id/contactID"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView android:id="@+id/contactNumber"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

activity_provider2.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Provider2Activity">

    <ListView

        android:id="@android:id/list"

        android:layout_height="wrap_content"

        android:layout_width="match_parent">

    </ListView>

</RelativeLayout>

Please try this below mentioned code will help you out...

`Uri contactdate = data.getData();
                Cursor cursor = managedQuery(contactdate, null, null, null,null);
                if(cursor.moveToFirst()){
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    if(hasPhone.equalsIgnoreCase("1")){
                        Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null,null);
                        phones.moveToFirst();
                        String phoneNumebr = phones.getString(phones.getColumnIndex("data1"));
                        String mFormatedPhoneNumber = phoneNumebr.replace("-", "").replace(" ", "").replace("(","").replace(")", "");
                        Log.i(TAG, "Phone Number :"+mFormatedPhoneNumber);                      

}else{ Log.i(TAG, "Phone Number Not available"); } Log.i(TAG, "Name :"+cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))); }`
Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .