How to write and to update a contact user retrieve ??

Theo Gballou 1 Reputation point
2020-12-21T19:24:36.547+00:00

hi community, i wanted to submit a problem to you, i am having some ambiguities on understanding how to write a contact in a user's directory or edit a contact in the phone directory. I want to do it by the selection of the contact modified, I have already solved the problem of the selection of the contact, the problem of the contact recovery and it works well on the other hand how to use the selected contact and then modify it added in the directory I do not see too much. I have all the permissions which are ok in my androidManifest so If someone could help me. Below I give you by detailing the tasks that I would like to do I will number them below.
1 _ Modify a selected contact (name and number) and save it in the directory with a new name and a new number.
2 _ Create a new contact by one method and save it in the directory.

this my code to select and i use a method update

namespace ContactListSample.ViewModels
{

public class SelectedContactsViewModel : Contact

{
IContactService _contactsService;
INavigation _navigation;

public int NbrContact; //nombre de contact selected

public int NbrContactEdit;

public ICommand NavigationCommandEdit { get; set; }


private ObservableCollection<Contact> _selectedContactList;
public ObservableCollection<Contact> SelectedContactList
{
    get
    {
        return _selectedContactList;
    }
    set
    {
        _selectedContactList = value;
        OnPropertyChanged("SelectedContactList");
    }
}


public SelectedContactsViewModel(List<Contact> SelectedList, IContactService _contactsService, INavigation _navigation, int NbrContact)
{
    SelectedContactList = new ObservableCollection<Contact>(SelectedList);

    /*_navigation = navigation;
    _contactService = contactsService;*/

    NavigationCommandEdit = new Command(() => Navigation_PageAsync());



}

void Navigation_PageAsync()
{

    UpdateContact();

    if (SelectedContactList.Count > 0)
    {

        var SelectedContactEdit = SelectedContactList.Where(x => x.IsSelected == true);
        SelectedContactEdit.ToArray();
        Console.WriteLine(SelectedContactEdit); 
        this._navigation.PopToRootAsync();
    }
    else
    {

        Console.WriteLine("ERREUR");
    }


 }


void UpdateContact()
{


    foreach (var element in SelectedContactList.ToList())
    {

        List<ContentProviderOperation> ops = new List<ContentProviderOperation>();

        // Name 
        string nameSelection = ContactsContract.Data.InterfaceConsts.Id + " = ? AND "
                          + ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
        string[] nameSelectionArgs = {

                            element.Name[0].ToString(),
                            ContactsContract.CommonDataKinds.StructuredName.ContentItemType
                            };

        ContentProviderOperation.Builder builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
        builder.WithSelection(nameSelection, nameSelectionArgs);
        builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, "chris");
        ops.Add(builder.Build());

        // Phone
        string phoneSelection = ContactsContract.Data.InterfaceConsts.Id + " = ? AND "
                                + ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
        string[] phoneelectionArgs = {

                           element.PhoneNumbers[0].ToString(),
                           ContactsContract.CommonDataKinds.Phone.ContentItemType
                           };

        builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
        builder.WithSelection(phoneSelection, phoneelectionArgs);
        builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, "999999");
        ops.Add(builder.Build());

        // Update the contact
        ContentProviderResult[] result;

        try
        {
            result = Android.App.Application.Context.ContentResolver.ApplyBatch(ContactsContract.Authority, ops);

            System.Diagnostics.Debug.WriteLine("CONTACT MODIFIÉ AVEC SUCCES");
            //DisplayAlert("Erreur", "Erreur reseau s'est produite:" + ex.Message, "OK");
        }
        catch
        {

            System.Diagnostics.Debug.WriteLine("CONTACT NON MODIFIÉ ");
        }
    }
}

}
}

Please offer me something simple to perform my tasks and make my application work.
Thank you all, I'm counting on you.

this is my IcontactService :

public class ContactService : IContactService
{

const string ThumbnailPrefix = "thumb";
bool stopLoad = false;
static TaskCompletionSource<bool> contactPermissionTcs;
public string TAG
{
    get
    {
        return "MainActivity";
    }
}
bool _isLoading = false;
public bool IsLoading => _isLoading;

public const int REQUEST_CONTACTS = 1239;

static string[] PERMISSIONS_CONTACT = {

    Manifest.Permission.ReadContacts,
    Manifest.Permission.WriteContacts,
    Manifest.Permission.ReadProfile,
    Manifest.Permission.WriteProfile
};


public event EventHandler<ContactEventArgs> OnContactLoaded;

async void RequestContactsPermissions()
{
    if (ActivityCompat.ShouldShowRequestPermissionRationale(CrossCurrentActivity.Current.Activity, Manifest.Permission.ReadContacts)
        || ActivityCompat.ShouldShowRequestPermissionRationale(CrossCurrentActivity.Current.Activity, Manifest.Permission.WriteContacts)
        || ActivityCompat.ShouldShowRequestPermissionRationale(CrossCurrentActivity.Current.Activity, Manifest.Permission.ReadProfile)
        || ActivityCompat.ShouldShowRequestPermissionRationale(CrossCurrentActivity.Current.Activity, Manifest.Permission.WriteProfile))
    {

        // Provide an additional rationale to the user if the permission was not granted
        // and the user would benefit from additional context for the use of the permission.
        // For example, if the request has been denied previously.

        await UserDialogs.Instance.AlertAsync("Contacts Permission", "This action requires contacts permission", "Ok");
    }
    else
    {
        // Contact permissions have not been granted yet. Request them directly.
        ActivityCompat.RequestPermissions(CrossCurrentActivity.Current.Activity, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
    }
}
public static void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    if (requestCode == ContactService.REQUEST_CONTACTS)
    {
        // We have requested multiple permissions for contacts, so all of them need to be
        // checked.
        if (PermissionUtil.VerifyPermissions(grantResults))
        {
            // All required permissions have been granted, display contacts fragment.
            contactPermissionTcs.TrySetResult(true);
        }
        else
        {
            contactPermissionTcs.TrySetResult(false);
        }

    }
}

public async Task<bool> RequestPermissionAsync()
{
    contactPermissionTcs = new TaskCompletionSource<bool>();
    // Verify that all required contact permissions have been granted.
    if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.ReadContacts) != (int)Permission.Granted
        || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.WriteContacts) != (int)Permission.Granted
        || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.ReadProfile) != (int)Permission.Granted
        || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(CrossCurrentActivity.Current.Activity, Manifest.Permission.WriteProfile) != (int)Permission.Granted)
    {
        // Contacts permissions have not been granted.
        RequestContactsPermissions();
    }
    else
    {
        // Contact permissions have been granted. 
        contactPermissionTcs.TrySetResult(true);
    }

    return await contactPermissionTcs.Task;
}

public async Task<IList<Contact>> RetrieveContactsAsync(CancellationToken? cancelToken = null)
{
    stopLoad = false;

    if (!cancelToken.HasValue)
        cancelToken = CancellationToken.None;

    // We create a TaskCompletionSource of decimal
    var taskCompletionSource = new TaskCompletionSource<IList<Contact>>();

    // Registering a lambda into the cancellationToken
    cancelToken.Value.Register(() =>
    {
        // We received a cancellation message, cancel the TaskCompletionSource.Task
        stopLoad = true;
        taskCompletionSource.TrySetCanceled();
    });

    _isLoading = true;

    var task = LoadContactsAsync();

    // Wait for the first task to finish among the two
    var completedTask = await Task.WhenAny(task, taskCompletionSource.Task);
    _isLoading = false;

    return await completedTask;
}


async Task<IList<Contact>> LoadContactsAsync()
{
    IList<Contact> contacts = new List<Contact>();

    var hasPermission = await RequestPermissionAsync();

    if (hasPermission)
    {
        //PERMISSION I HAVE EDIT
        var uri = ContactsContract.Contacts.ContentUri;
        var ctx = Android.App.Application.Context;

        await Task.Run(() =>
        {
            var cursor = ctx.ApplicationContext.ContentResolver.Query(uri, new string[]
            {
                ContactsContract.Contacts.InterfaceConsts.Id,
                ContactsContract.Contacts.InterfaceConsts.DisplayName,
                ContactsContract.Contacts.InterfaceConsts.PhotoThumbnailUri
            }, null, null, $"{ContactsContract.Contacts.InterfaceConsts.DisplayName} ASC");

            if (cursor.Count > 0)
            {
                while (cursor.MoveToNext())
                {
                    var contact = CreateContact(cursor, ctx);

                    if (!string.IsNullOrWhiteSpace(contact.Name))
                    {
                        OnContactLoaded?.Invoke(this, new ContactEventArgs(contact));
                        contacts.Add(contact);
                    }

                    if (stopLoad)
                        break;
                }
            }
        });

    }
    return contacts;

}

Contact CreateContact(ICursor cursor, Context ctx)
{
    var contactId = GetString(cursor, ContactsContract.Contacts.InterfaceConsts.Id);

    var numbers = GetNumbers(ctx, contactId);
    //var emails = GetEmails(ctx, contactId);

    var uri = GetString(cursor, ContactsContract.Contacts.InterfaceConsts.PhotoThumbnailUri);
    string path = null;
    if (!string.IsNullOrEmpty(uri))
    {
        try
        {
            using (var stream = Android.App.Application.Context.ContentResolver.OpenInputStream(Android.Net.Uri.Parse(uri)))
            {
                //path = FileHelper.GetOutputPath(FileHelper.TemporalDirectoryName, $"{FileHelper.ThumbnailPrefix}-{Guid.NewGuid()}");
                path = Path.Combine(Path.GetTempPath(), $"{ThumbnailPrefix}-{Guid.NewGuid()}");

                using (var fstream = new FileStream(path, FileMode.Create))
                {
                    stream.CopyTo(fstream);
                    fstream.Close();
                }

                stream.Close();
            }


        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }

    }
    var contact = new Contact
    {
        Name = GetString(cursor, ContactsContract.Contacts.InterfaceConsts.DisplayName),
        //Emails = emails,
        //Image = path,
        PhoneNumbers = numbers,
    };

    return contact;
}


string[] GetNumbers(Context ctx, string contactId)
{
    var key = ContactsContract.CommonDataKinds.Phone.Number;

    var cursor = ctx.ApplicationContext.ContentResolver.Query(
        ContactsContract.CommonDataKinds.Phone.ContentUri,
        null,
        ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + " = ?",
        new[] { contactId },
        null
    );

    return ReadCursorItems(cursor, key)?.ToArray();
}

string[] GetEmails(Context ctx, string contactId)
{
    var key = ContactsContract.CommonDataKinds.Email.InterfaceConsts.Data;

    var cursor = ctx.ApplicationContext.ContentResolver.Query(
        ContactsContract.CommonDataKinds.Email.ContentUri,
        null,
        ContactsContract.CommonDataKinds.Email.InterfaceConsts.ContactId + " = ?",
        new[] { contactId },
        null);

    return ReadCursorItems(cursor, key)?.ToArray();
}

IEnumerable<string> ReadCursorItems(ICursor cursor, string key)
{
    while (cursor.MoveToNext())
    {
        var value = GetString(cursor, key);
        yield return value;
    }

    cursor.Close();
}

string GetString(ICursor cursor, string key)
{
    return cursor.GetString(cursor.GetColumnIndex(key));
}


static IEnumerable<Contact> _contactsList;

}

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,288 questions
{count} votes