Example usage for android.provider ContactsContract AUTHORITY

List of usage examples for android.provider ContactsContract AUTHORITY

Introduction

In this page you can find the example usage for android.provider ContactsContract AUTHORITY.

Prototype

String AUTHORITY

To view the source code for android.provider ContactsContract AUTHORITY.

Click Source Link

Document

The authority for the contacts provider

Usage

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

private void turnSyncOn() {
    final ContactListFilter filter = getFilter();
    if (filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT
            && mReasonSyncOff == SyncUtil.SYNC_SETTING_ACCOUNT_SYNC_OFF) {
        ContentResolver.setSyncAutomatically(new Account(filter.accountName, filter.accountType),
                ContactsContract.AUTHORITY, true);
        mAlertContainer.setVisibility(View.GONE);
    } else {//from w w  w . ja  va2 s  .  c o m
        final EnableGlobalSyncDialogFragment dialog = new EnableGlobalSyncDialogFragment();
        dialog.show(this, filter);
    }
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

@Override
public void onEnableAutoSync(ContactListFilter filter) {
    // Turn on auto-sync
    ContentResolver.setMasterSyncAutomatically(true);

    // This should be OK (won't block) because this only happens after a user action
    final List<AccountInfo> accountInfos = Futures.getUnchecked(mWritableAccountsFuture);
    // Also enable Contacts sync
    final List<AccountWithDataSet> accounts = AccountInfo.extractAccounts(accountInfos);
    final List<Account> syncableAccounts = filter.getSyncableAccounts(accounts);
    if (syncableAccounts != null && syncableAccounts.size() > 0) {
        for (Account account : syncableAccounts) {
            ContentResolver.setSyncAutomatically(new Account(account.name, account.type),
                    ContactsContract.AUTHORITY, true);
        }/*from ww w .ja va  2s .  co m*/
    }
    mAlertContainer.setVisibility(View.GONE);
}

From source file:com.ibuildapp.romanblack.MultiContactsPlugin.ContactDetailsActivity.java

/**
 * Saves given contact to device phone book.
 *
 * @param name         contact name to save
 * @param MobileNumber contact mobile number to save
 * @param emailID      contact email address to save
 *//* w ww.  ja va2s  . c  o  m*/
private void createNewContact(String name, String MobileNumber, String emailID) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

    //------------------------------------------------------ Names
    if (name != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name).build());
    }

    //------------------------------------------------------ Mobile Number
    if (MobileNumber != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build());
    }

    //------------------------------------------------------ Email
    if (emailID != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                .build());
    }

    // Asking the Contact provider to create a new contact
    try {
        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        Toast.makeText(this, getResources().getString(R.string.romanblack_multicontacts_alert_contact_added),
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this,
                getResources().getString(R.string.romanblack_multicontacts_alert_contact_added_error),
                Toast.LENGTH_SHORT).show();
    }
}

From source file:com.android.messaging.datamodel.BugleNotifications.java

/**
 * Returns the thumbnailUri from the avatar URI, or null if avatar URI does not have thumbnail.
 *///  w w  w. ja  v  a 2  s.c o  m
private static Uri getThumbnailUri(final Uri avatarUri) {
    Uri localUri = null;
    final String avatarType = AvatarUriUtil.getAvatarType(avatarUri);
    if (TextUtils.equals(avatarType, AvatarUriUtil.TYPE_LOCAL_RESOURCE_URI)) {
        localUri = AvatarUriUtil.getPrimaryUri(avatarUri);
    } else if (UriUtil.isLocalResourceUri(avatarUri)) {
        localUri = avatarUri;
    }
    if (localUri != null && localUri.getAuthority().equals(ContactsContract.AUTHORITY)) {
        // Contact photos are of the form: content://com.android.contacts/contacts/123/photo
        final List<String> pathParts = localUri.getPathSegments();
        if (pathParts.size() == 3 && pathParts.get(2).equals(Contacts.Photo.CONTENT_DIRECTORY)) {
            return localUri;
        }
    }
    return null;
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private void syncGroupsWithServer(ContentProviderClient provider, String authToken, Account account,
        SyncResult syncResult) throws JSONException, RemoteException, IOException {
    JSONArray groupArray = NetworkUtilities.getMyOwnedGroups(authToken);
    if (groupArray == null) {
        syncResult.delayUntil = 180;/*from  w  w  w . j  a  v a 2s  .  c o  m*/
        return;
    }
    ContentProviderClient contactsProvider = this.getContext().getContentResolver()
            .acquireContentProviderClient(ContactsContract.AUTHORITY);
    for (int i = 0; i < groupArray.length(); ++i) {
        JSONObject group = groupArray.getJSONObject(i);
        try {
            optimisticallyCreateGroupAndContacts(group, provider, contactsProvider, authToken, account,
                    syncResult);
        } catch (OperationApplicationException e) {
            // We're here because our assertion about there being no group failed
            optimisticallyUpdateGroup(group, provider, contactsProvider, authToken, account, syncResult);
            optimisticallyAddContactsToExistingGroup(group, provider, authToken, account, syncResult);
        }
    }
    deleteUnsyncedItems(provider, account, syncResult);
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

/**
 * Request sync for the Google accounts (not include Google+ accounts) specified by the given
 * filter./*from w ww  . jav a 2 s . c  om*/
 */
private void syncContacts(ContactListFilter filter) {
    if (filter == null) {
        return;
    }

    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);

    final List<AccountWithDataSet> accounts = AccountInfo
            .extractAccounts(Futures.getUnchecked(mWritableAccountsFuture));
    final List<Account> syncableAccounts = filter.getSyncableAccounts(accounts);
    if (syncableAccounts != null && syncableAccounts.size() > 0) {
        for (Account account : syncableAccounts) {
            // We can prioritize Contacts sync if sync is not initialized yet.
            if (!SyncUtil.isSyncStatusPendingOrActive(account) || SyncUtil.isUnsyncableGoogleAccount(account)) {
                ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
            }
        }
    }
}

From source file:at.bitfire.davdroid.ui.AccountActivity.java

protected static void requestSync(Account account) {
    String authorities[] = { ContactsContract.AUTHORITY, CalendarContract.AUTHORITY,
            TaskProvider.ProviderName.OpenTasks.authority };

    for (String authority : authorities) {
        Bundle extras = new Bundle();
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // manual sync
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // run immediately (don't queue)
        ContentResolver.requestSync(account, authority, extras);
    }/*from   w w w .  ja v a  2s .  com*/
}

From source file:com.android.exchange.EasAccountService.java

private void runPingLoop()
        throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException {
    int pingHeartbeat = mPingHeartbeat;
    userLog("runPingLoop");
    // Do push for all sync services here
    long endTime = System.currentTimeMillis() + (30 * DateUtils.MINUTE_IN_MILLIS);
    HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    ArrayList<String> readyMailboxes = new ArrayList<String>();
    ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    int pingWaitCount = 0;
    long inboxId = -1;
    android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress,
            Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
    while ((System.currentTimeMillis() < endTime) && !isStopped()) {
        // Count of pushable mailboxes
        int pushCount = 0;
        // Count of mailboxes that can be pushed right now
        int canPushCount = 0;
        // Count of uninitialized boxes
        int uninitCount = 0;

        Serializer s = new Serializer();
        Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
                MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId
                        + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX,
                null, null);//  w w  w .  j  ava  2s . c  o m
        if (c == null)
            throw new ProviderUnavailableException();
        notReadyMailboxes.clear();
        readyMailboxes.clear();
        // Look for an inbox, and remember its id
        if (inboxId == -1) {
            inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
        }
        try {
            // Loop through our pushed boxes seeing what is available to push
            while (c.moveToNext()) {
                pushCount++;
                // Two requirements for push:
                // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
                // 2) The syncKey isn't "0" (i.e. it's synced at least once)
                long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
                String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);

                // See what type of box we've got and get authority
                int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
                String authority = EmailContent.AUTHORITY;
                switch (mailboxType) {
                case Mailbox.TYPE_CALENDAR:
                    authority = CalendarContract.AUTHORITY;
                    break;
                case Mailbox.TYPE_CONTACTS:
                    authority = ContactsContract.AUTHORITY;
                    break;
                }

                // See whether we can ping for this mailbox
                int pingStatus;
                if (!ContentResolver.getSyncAutomatically(amAccount, authority)) {
                    pingStatus = ExchangeService.PING_STATUS_DISABLED;
                } else {
                    pingStatus = ExchangeService.pingStatus(mailboxId);

                }

                if (pingStatus == ExchangeService.PING_STATUS_OK) {
                    String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
                    if ((syncKey == null) || syncKey.equals("0")) {
                        // We can't push until the initial sync is done
                        pushCount--;
                        uninitCount++;
                        continue;
                    }

                    if (canPushCount++ == 0) {
                        // Initialize the Ping command
                        s.start(Tags.PING_PING)
                                .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat))
                                .start(Tags.PING_FOLDERS);
                    }

                    String folderClass = getTargetCollectionClassFromCursor(c);
                    s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
                            .data(Tags.PING_CLASS, folderClass).end();
                    readyMailboxes.add(mailboxName);
                } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING)
                        || (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
                    notReadyMailboxes.add(mailboxName);
                } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
                    pushCount--;
                    userLog(mailboxName, " in error state; ignore");
                    continue;
                } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) {
                    pushCount--;
                    userLog(mailboxName, " disabled by user; ignore");
                    continue;
                }
            }
        } finally {
            c.close();
        }

        if (Eas.USER_LOG) {
            if (!notReadyMailboxes.isEmpty()) {
                userLog("Ping not ready for: " + notReadyMailboxes);
            }
            if (!readyMailboxes.isEmpty()) {
                userLog("Ping ready for: " + readyMailboxes);
            }
        }

        // If we've waited 10 seconds or more, just ping with whatever boxes are ready
        // But use a shorter than normal heartbeat
        boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);

        if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
            // If all pingable boxes are ready for push, send Ping to the server
            s.end().end().done();
            pingWaitCount = 0;
            mPostAborted = false;
            mPostReset = false;

            // If we've been stopped, this is a good time to return
            if (isStopped())
                return;

            long pingTime = SystemClock.elapsedRealtime();
            try {
                // Send the ping, wrapped by appropriate timeout/alarm
                if (forcePing) {
                    userLog("Forcing ping after waiting for all boxes to be ready");
                }
                EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);

                try {
                    int code = resp.getStatus();
                    userLog("Ping response: ", code);

                    // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
                    // now; otherwise we might start a sync based on the response
                    if (!ExchangeService.canAutoSync(mAccount)) {
                        stop();
                    }

                    // Return immediately if we've been asked to stop during the ping
                    if (isStopped()) {
                        userLog("Stopping pingLoop");
                        return;
                    }

                    if (code == HttpStatus.SC_OK) {
                        if (!resp.isEmpty()) {
                            InputStream is = resp.getInputStream();
                            int pingResult = parsePingResult(is, mContentResolver, pingErrorMap);
                            // If our ping completed (status = 1), and wasn't forced and we're
                            // not at the maximum, try increasing timeout by two minutes
                            if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
                                if (pingHeartbeat > mPingHighWaterMark) {
                                    mPingHighWaterMark = pingHeartbeat;
                                    userLog("Setting high water mark at: ", mPingHighWaterMark);
                                }
                                if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) {
                                    pingHeartbeat += PING_HEARTBEAT_INCREMENT;
                                    if (pingHeartbeat > mPingMaxHeartbeat) {
                                        pingHeartbeat = mPingMaxHeartbeat;
                                    }
                                    userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
                                }
                            } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS
                                    || pingResult == PROTOCOL_PING_STATUS_RETRY) {
                                // These errors appear to be server-related (I've seen a bad
                                // parameters result with known good parameters...)
                                userLog("Server error during Ping: " + pingResult);
                                // Act as if we have an IOException (backoff, etc.)
                                throw new IOException();
                            }
                            // Make sure to clear out any pending sync errors
                            ExchangeService.removeFromSyncErrorMap(mMailboxId);
                        } else {
                            userLog("Ping returned empty result; throwing IOException");
                            // Act as if we have an IOException (backoff, etc.)
                            throw new IOException();
                        }
                    } else if (resp.isAuthError()) {
                        mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
                        userLog("Authorization error during Ping: ", code);
                        throw new IOException();
                    }
                } finally {
                    resp.close();
                }
            } catch (IOException e) {
                String message = e.getMessage();
                // If we get the exception that is indicative of a NAT timeout and if we
                // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
                boolean hasMessage = message != null;
                userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
                if (mPostReset) {
                    // Nothing to do in this case; this is ExchangeService telling us to try
                    // another ping.
                } else if (mPostAborted || isLikelyNatFailure(message)) {
                    long pingLength = SystemClock.elapsedRealtime() - pingTime;
                    if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) {
                        pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
                        mPingHeartbeatDropped = true;
                        if (pingHeartbeat < mPingMinHeartbeat) {
                            pingHeartbeat = mPingMinHeartbeat;
                        }
                        userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
                    } else if (mPostAborted) {
                        // There's no point in throwing here; this can happen in two cases
                        // 1) An alarm, which indicates minutes without activity; no sense
                        //    backing off
                        // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
                        //    keep on trying to ping
                        userLog("Ping aborted; retry");
                    } else if (pingLength < 2000) {
                        userLog("Abort or NAT type return < 2 seconds; throwing IOException");
                        throw e;
                    } else {
                        userLog("NAT type IOException");
                    }
                } else if (hasMessage && message.contains("roken pipe")) {
                    // The "broken pipe" error (uppercase or lowercase "b") seems to be an
                    // internal error, so let's not throw an exception (which leads to delays)
                    // but rather simply run through the loop again
                } else {
                    throw e;
                }
            }
        } else if (forcePing) {
            // In this case, there aren't any boxes that are pingable, but there are boxes
            // waiting (for IOExceptions)
            userLog("pingLoop waiting 60s for any pingable boxes");
            sleep(60 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (pushCount > 0) {
            // If we want to Ping, but can't just yet, wait a little bit
            // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
            sleep(2 * DateUtils.SECOND_IN_MILLIS, false);
            pingWaitCount++;
            //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
        } else if (uninitCount > 0) {
            // In this case, we're doing an initial sync of at least one mailbox.  Since this
            // is typically a one-time case, I'm ok with trying again every 10 seconds until
            // we're in one of the other possible states.
            userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
            sleep(10 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (inboxId == -1) {
            // In this case, we're still syncing mailboxes, so sleep for only a short time
            sleep(45 * DateUtils.SECOND_IN_MILLIS, true);
        } else {
            // We've got nothing to do, so we'll check again in 20 minutes at which time
            // we'll update the folder list, check for policy changes and/or remote wipe, etc.
            // Let the device sleep in the meantime...
            userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
            sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
        }
    }

    // Save away the current heartbeat
    mPingHeartbeat = pingHeartbeat;
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From//from  w w w  .ja  v  a2s . c om
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @param phone From
 * {@link android.provider.ContactsContract.CommonDataKinds.Phone#NUMBER}
 * @param data1 From
 * {@link android.provider.ContactsContract.Data#DATA1}
 * @param _id From
 * {@link android.provider.ContactsContract#}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address,
        final String phone, final String data1, final String _id, final String _name) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);
    final TextView phoneTextView = (TextView) addressLayout.findViewById(R.id.contact_phone);
    final SeekBar levelSeekBar = (SeekBar) addressLayout.findViewById(R.id.contact_level);
    final ImageButton saveButton = (ImageButton) addressLayout.findViewById(R.id.button_save);

    Integer prioridad = Integer.parseInt(data1 == null ? "4" : data1);
    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0 && phone == null) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);
        phoneTextView.setText(phone);
        levelSeekBar.setProgress(prioridad);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Defines an onClickListener object for the save button
        saveButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                // Creates a new intent for sending to the device's contacts application
                // Creates a new array of ContentProviderOperation objects.
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                Integer prioridad = levelSeekBar.getProgress();
                Log.d("ContactDetalFragment", _id);

                ContentProviderOperation.Builder op;
                if (data1 == null) {
                    Uri uri = addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true);
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, _name)
                            .build());

                    op = ContentProviderOperation.newInsert(Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(Data.DATA1, prioridad).withValue(Data.MIMETYPE, LEVEL_MIME_TYPE);

                } else {
                    String where = Data.MIMETYPE + " = ? ";
                    String[] params = new String[] { LEVEL_MIME_TYPE, };

                    op = ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(where, params)
                            .withValue(Data.DATA1, prioridad);

                }
                ops.add(op.build());
                try {
                    ContentProviderResult[] results = view.getContext().getContentResolver()
                            .applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                    CharSequence txt = getString(R.string.contactUpdateFailure);
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(view.getContext(), txt, duration);
                    toast.show();
                    // Log exception
                    Log.e(TAG, "Exception encountered while inserting contact: " + e);
                }
            }
        });

    }
    return addressLayout;
}