Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

In this page you can find the example usage for android.content ContentResolver insert.

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

From source file:org.getlantern.firetweet.util.Utils.java

public static void updateRelationship(Context context, Relationship relationship, long accountId) {
    final ContentResolver resolver = context.getContentResolver();
    final ContentValues values = ContentValuesCreator.createCachedRelationship(relationship, accountId);
    resolver.insert(CachedRelationships.CONTENT_URI, values);
}

From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java

/**
 * Adds or removes a single session to/from the specified Google Calendar.
 *//*w  w  w .  ja v a2 s . co m*/
private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver,
        final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart,
        final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Unable to find the Calendar associated with the user or permissions were revoked.
    if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) {
        return batch;
    }

    final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);

    Cursor cursor;
    ContentValues values = new ContentValues();

    // Add Calendar event.
    if (isAddEvent) {
        if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
            LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
            return batch;
        }

        // Check if the calendar event exists first.  If it does, we don't want to add a
        // duplicate one.
        //noinspection MissingPermission
        cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI
                new String[] { CalendarContract.Events._ID }, // Projection
                CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
                        + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART
                        + ">=? and " + CalendarContract.Events.DTEND + "<=?",
                new String[] { // Selection args
                        Long.valueOf(calendarId).toString(), calendarEventTitle,
                        Long.toString(Config.CONFERENCE_START_MILLIS),
                        Long.toString(Config.CONFERENCE_END_MILLIS) },
                null);

        long newEventId = -1;

        if (cursor != null && cursor.moveToFirst()) {
            // Calendar event already exists for this session.
            newEventId = cursor.getLong(0);
            cursor.close();

            // Data fix (workaround):
            batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI)
                    .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID())
                    .withSelection(CalendarContract.Events._ID + "=?",
                            new String[] { Long.valueOf(newEventId).toString() })
                    .build());
            // End data fix.

        } else {
            // Calendar event doesn't exist, create it.

            // NOTE: we can't use batch processing here because we need the result of
            // the insert.
            values.clear();
            values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
            values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
            values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
            values.put(CalendarContract.Events.TITLE, calendarEventTitle);
            values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID());
            @SuppressWarnings("MissingPermission")
            Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
            String eventId = eventUri.getLastPathSegment();
            if (eventId == null) {
                return batch; // Should be empty at this point
            }

            newEventId = Long.valueOf(eventId);
            // Since we're adding session reminder to system notification, we're not creating
            // Calendar event reminders.  If we were to create Calendar event reminders, this
            // is how we would do it.
            //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
            //values.put(CalendarContract.Reminders.MINUTES, 10);
            //values.put(CalendarContract.Reminders.METHOD,
            //        CalendarContract.Reminders.METHOD_ALERT); // Or default?
            //cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
            //values.clear();
        }

        // Update the session in our own provider with the newly created calendar event ID.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
        resolver.update(sessionUri, values, null, null);

    } else {
        // Remove Calendar event, if exists.

        // Get the event calendar id.
        cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID },
                null, null, null);
        long calendarEventId = -1;
        if (cursor != null && cursor.moveToFirst()) {
            calendarEventId = cursor.getLong(0);
            cursor.close();
        }

        // Try to remove the Calendar Event based on key.  If successful, move on;
        // otherwise, remove the event based on Event title.
        int affectedRows = 0;
        if (calendarEventId != -1) {
            //noinspection MissingPermission
            affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI,
                    CalendarContract.Events._ID + "=?",
                    new String[] { Long.valueOf(calendarEventId).toString() });
        }

        if (affectedRows == 0) {
            //noinspection MissingPermission
            resolver.delete(CalendarContract.Events.CONTENT_URI,
                    String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID,
                            CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART,
                            CalendarContract.Events.DTEND),
                    new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle,
                            Long.valueOf(sessionBlockStart).toString(),
                            Long.valueOf(sessionBlockEnd).toString() });
        }

        // Remove the session and calendar event association.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
        resolver.update(sessionUri, values, null, null);
    }

    return batch;
}

From source file:com.akop.bach.parser.PsnEuParser.java

@SuppressLint("DefaultLocale")
@Override//from w  w  w  . j  a  v  a 2 s  .c  o  m
protected void parseFriendSummary(PsnAccount account, String friendOnlineId)
        throws ParserException, IOException {
    String url = String.format(URL_FRIEND_SUMMARY_f, URLEncoder.encode(friendOnlineId, "UTF-8"));
    String friendData = getResponse(url);

    ContentResolver cr = mContext.getContentResolver();
    Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
            Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
            new String[] { friendOnlineId }, null);

    long updated = System.currentTimeMillis();
    long started = updated;
    long friendId = -1;

    try {
        if (c != null && c.moveToFirst())
            friendId = c.getLong(0);
    } finally {
        if (c != null)
            c.close();
    }

    Matcher m;
    Matcher friendMatcher = PATTERN_FRIEND_SUMMARY.matcher(friendData);
    if (friendMatcher.find() && friendMatcher.find()) // skip the first
    {
        String friendCard = friendMatcher.group(1);

        String onlineId = null;
        if ((m = PATTERN_FRIEND_SUMMARY_ONLINE_ID.matcher(friendCard)).find())
            onlineId = htmlDecode(m.group(1));

        if (onlineId != null) {
            int progress = 0;
            if ((m = PATTERN_FRIEND_SUMMARY_PROGRESS.matcher(friendCard)).find())
                progress = Integer.parseInt(m.group(1));

            int level = 0;
            if ((m = PATTERN_FRIEND_SUMMARY_LEVEL.matcher(friendCard)).find())
                level = Integer.parseInt(m.group(1));

            String iconUrl = null;
            if ((m = PATTERN_FRIEND_SUMMARY_AVATAR.matcher(friendCard)).find())
                iconUrl = getLargeAvatarIcon(resolveImageUrl(url, m.group(1)));

            int memberType = PSN.MEMBER_TYPE_FREE;
            if ((m = PATTERN_FRIEND_SUMMARY_IS_PLUS.matcher(friendCard)).find())
                memberType = PSN.MEMBER_TYPE_PLUS;

            int bronze = 0;
            int silver = 0;
            int gold = 0;
            int platinum = 0;

            m = PATTERN_FRIEND_SUMMARY_TROPHIES.matcher(friendCard);
            while (m.find()) {
                String type = m.group(1).toLowerCase();
                if ("bronze".equals(type))
                    bronze = Integer.parseInt(m.group(2));
                else if ("silver".equals(type))
                    silver = Integer.parseInt(m.group(2));
                else if ("gold".equals(type))
                    gold = Integer.parseInt(m.group(2));
                else if ("platinum".equals(type))
                    platinum = Integer.parseInt(m.group(2));
            }

            ContentValues cv = new ContentValues(15);

            cv.put(Friends.LAST_UPDATED, updated);
            cv.put(Friends.ONLINE_ID, onlineId);
            cv.put(Friends.ICON_URL, iconUrl);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.PROGRESS, progress);
            cv.put(Friends.TROPHIES_PLATINUM, platinum);
            cv.put(Friends.TROPHIES_GOLD, gold);
            cv.put(Friends.TROPHIES_SILVER, silver);
            cv.put(Friends.TROPHIES_BRONZE, bronze);
            cv.put(Friends.MEMBER_TYPE, memberType);

            if (friendId < 0) {
                // New
                cv.put(Friends.ACCOUNT_ID, account.getId());
                cv.put(Friends.ONLINE_STATUS, PSN.STATUS_OTHER);
                cv.put(Friends.PLAYING, (String) null);

                cr.insert(Friends.CONTENT_URI, cv);
            } else {
                // Existing
                cr.update(Friends.CONTENT_URI, cv, Friends._ID + "=" + friendId, null);
            }

            cr.notifyChange(Friends.CONTENT_URI, null);
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("parseCompareGames/processing", started);
}

From source file:com.vegnab.vegnab.MainVNActivity.java

void logPurchaseActivity(Purchase p, IabResult result, boolean isConsumed, String notes) {
    Uri uri, purchUri = Uri.withAppendedPath(ContentProvider_VegNab.CONTENT_URI, "purchases");
    ContentResolver rs = getContentResolver();
    ContentValues contentValues = new ContentValues();
    if (p == null) {
        contentValues.put("ProductIdCode", "(purchase object is null)");
        contentValues.put("Type", "null");
        contentValues.put("PurchaseState", -2); // purchase is null
    } else {//from w w  w  . j a  v a2 s.c o m
        String sku = p.getSku();
        contentValues.put("ProductIdCode", sku); // also called 'SKU'
        contentValues.put("DevPayload", p.getDeveloperPayload());
        contentValues.put("Type", p.getItemType()); // "inapp" for an in-app product or "subs" for subscriptions.
        contentValues.put("OrderIDCode", p.getOrderId());
        // corresponds to the Google payments order ID
        contentValues.put("PkgName", p.getPackageName());
        contentValues.put("Signature", p.getSignature());
        contentValues.put("Token", p.getToken());
        // uniquely identifies a purchase for a given item and user pair
        contentValues.put("PurchaseState", p.getPurchaseState());
        // standard: 0 (purchased), 1 (canceled), or 2 (refunded). or nonstandard: -1 (initiated), -2 (null)
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        long t = p.getPurchaseTime();
        contentValues.put("PurchaseTime", dateTimeFormat.format(new Date(t)));
        contentValues.put("PurchJSON", p.getOriginalJson());
        try { // inventory object may not exist yet
            if (mInventory.hasDetails(sku)) {
                SkuDetails skuDetails = mInventory.getSkuDetails(sku);
                contentValues.put("Price", skuDetails.getPrice());
                contentValues.put("Description", skuDetails.getDescription());
                contentValues.put("Title", skuDetails.getTitle());
            } else {
                contentValues.putNull("Price");
                contentValues.putNull("Description");
                contentValues.putNull("Title");
            }
        } catch (Exception e) {
            contentValues.putNull("Price");
            contentValues.putNull("Description");
            contentValues.putNull("Title");
        }
    }

    contentValues.put("Consumed", isConsumed ? 1 : 0);
    if (result == null) {
        contentValues.putNull("IABResponse");
        contentValues.putNull("IABMessage");
    } else {
        contentValues.put("IABResponse", result.getResponse());
        contentValues.put("IABMessage", result.getMessage());
    }
    if (notes == null) {
        contentValues.putNull("Notes");
    } else {
        contentValues.put("Notes", notes);
    }
    // create a new record
    uri = rs.insert(purchUri, contentValues);
    mNewPurcRecId = Long.parseLong(uri.getLastPathSegment());
    if (LDebug.ON)
        Log.d(LOG_TAG, "mNewPurcRecId of new record stored in DB: " + mNewPurcRecId);
}

From source file:edu.mit.mobile.android.locast.data.Sync.java

/**
 * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network,
 * attempt to sync.//from  w w  w.j av a 2  s  .  c om
 * Either c or cvNet can be null, but not both.
 * @param c A cursor pointing to the data item. Null is OK here.
 * @param jsonObject JSON object for the item as loaded from the network. null is OK here.
 * @param sync An empty JsonSyncableItem object.
 * @param publicPath TODO
 *
 * @return True if the item has been modified on either end.
 * @throws IOException
 */
private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync,
        SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException {
    boolean modified = false;
    boolean needToCloseCursor = false;
    boolean toSyncIsIndex = false;
    final SyncMap syncMap = sync.getSyncMap();

    Uri locUri = null;
    final Uri origToSync = toSync;
    ContentValues cvNet = null;

    final Context context = getApplicationContext();
    final ContentResolver cr = context.getContentResolver();
    if (jsonObject != null) {
        if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
            // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it.

            toSync = sync.getContentUri();
            if (toSync == null) {
                if (DEBUG) {
                    Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping...");
                }
                return false;
            }
        }
        try {
            cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
        } catch (final Exception e) {
            final SyncException se = new SyncException("Problem loading JSON object.");
            se.initCause(e);
            throw se;
        }
    }

    final String contentType = cr.getType(toSync);

    if (c != null) {
        if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            toSyncIsIndex = true;
        } else {
            locUri = toSync;
        }

        // skip any items already sync'd
        if (mLastUpdated.isUpdatedRecently(locUri)) {
            return false;
        }

        final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
        if (draftCol != -1 && c.getInt(draftCol) != 0) {
            if (DEBUG) {
                Log.d(TAG, locUri + " is marked a draft. Not syncing.");
            }
            return false;
        }

        syncMap.onPreSyncItem(cr, locUri, c);
    } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
        // strip any query strings
        toSync = toSync.buildUpon().query(null).build();
    }
    //      if (c != null){
    //         MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
    //      }
    // when the PUBLIC_URI is null, that means it's only local
    final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
    if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) {
        // new content on the local side only. Gotta publish.

        try {
            jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
            if (publicPath == null) {
                publicPath = MediaProvider.getPostPath(this, locUri);
            }
            if (DEBUG) {
                Log.d(TAG, "Posting " + locUri + " to " + publicPath);
            }

            // The response from a post to create a new item should be the newly created item,
            // which contains the public ID that we need.
            jsonObject = nc.postJson(publicPath, jsonObject);

            final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
            if (cr.update(locUri, cvUpdate, null, null) == 1) {
                // at this point, server and client should be in sync.
                mLastUpdated.markUpdated(locUri);
                if (DEBUG) {
                    Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully.");
                }

            } else {
                Log.e(TAG, "update of " + locUri + " failed");
            }
            modified = true;

        } catch (final Exception e) {
            final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
            se.initCause(e);
            throw se;
        }

        // only on the remote side, so pull it in.
    } else if (c == null && cvNet != null) {
        if (DEBUG) {
            Log.i(TAG, "Only on the remote side, using network-provided values.");
        }
        final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) };
        c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null);
        needToCloseCursor = true;

        if (!c.moveToFirst()) {
            locUri = cr.insert(toSync, cvNet);
            modified = true;
        } else {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            syncMap.onPreSyncItem(cr, locUri, c);
        }
    }

    // we've now found data on both sides, so sync them.
    if (!modified && c != null) {

        publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));

        try {

            if (cvNet == null) {
                try {
                    if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) {

                        // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
                        // If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
                        if (DEBUG) {
                            Log.w(TAG, "Asked to sync " + locUri
                                    + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
                        }
                        return false;

                    } else {
                        if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) {
                            if (DEBUG) {
                                Log.d(TAG, "already sync'd! " + publicPath);
                            }
                            return false;
                        }
                        if (jsonObject == null) {
                            jsonObject = nc.getObject(publicPath);
                        }
                        cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);

                    }
                } catch (final HttpResponseException hre) {
                    if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                        final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
                        side.initCause(hre);
                        throw side;
                    }
                }
            }
            if (cvNet == null) {
                Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": "
                        + (jsonObject != null ? jsonObject.toString() : "<< no json object >>"));
                return false;
            }
            final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
            final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));

            if (netLastModified.equals(locLastModified)) {
                // same! yay! We don't need to do anything.
                if (DEBUG) {
                    Log.d("LocastSync", locUri + " doesn't need to sync.");
                }
            } else if (netLastModified.after(locLastModified)) {
                // remote is more up to date, update!
                cr.update(locUri, cvNet, null, null);
                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is newer than " + locUri);
                }
                modified = true;

            } else if (netLastModified.before(locLastModified)) {
                // local is more up to date, propagate!
                jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));

                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is older than " + locUri);
                }
                modified = true;
            }
            mLastUpdated.markUpdated(nc.getFullUri(publicPath));
        } catch (final JSONException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": invalid JSON.");
            se.initCause(e);
            throw se;
        } catch (final NetworkProtocolException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage());
            se.initCause(e);
            throw se;
        } finally {
            if (needToCloseCursor) {
                c.close();
                needToCloseCursor = false;
            }
        }
    }

    if (needToCloseCursor) {
        c.close();
    }

    if (locUri == null) {
        throw new RuntimeException("Never got a local URI for a sync'd item.");
    }

    // two calls are made in two different contexts. Which context you use depends on the application.
    syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
    sync.onPostSyncItem(context, locUri, jsonObject, modified);

    mLastUpdated.markUpdated(locUri);

    // needed for things that may have requested a sync with a different URI than what was eventually produced.
    if (origToSync != locUri) {
        mLastUpdated.markUpdated(origToSync);
        cr.notifyChange(origToSync, null);
    }

    return modified;
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

public void showDialogAddContact(final String contacto) {
    final boolean[] agregar = { false };
    try {/*from ww w. j  av a 2 s .  c  om*/
        final ContentResolver contentResolver = activity.getContentResolver();
        final JSONObject contact = new JSONObject(contacto);
        String name = null;
        String phone = null;

        String selectionArgs = ContactsContract.Contacts.DISPLAY_NAME + " = ? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

        Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs,
                new String[] { contact.getString("nombre") }, null);

        if (c.getCount() > 0) {
            if (c.moveToFirst()) {
                phone = c.getString(0);
            }
            if (phone.equals(contact.getString("telefono"))) {
                Toast.makeText(activity, "Ya tienes este contacto", Toast.LENGTH_SHORT).show();
            } else {
                LayoutInflater dialogInflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                        .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                        .setNegativeButton(R.string.add_contact_no, null);
                finderDialog = dialogBuilder.show();
                finderDialog.setCanceledOnTouchOutside(true);
                finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    finderDialog.dismiss();
                                    agregar[0] = true;
                                    if (agregar[0]) {
                                        ContentValues values = new ContentValues();
                                        values.put(ContactsContract.Data.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        Uri rawContactUri = contentResolver
                                                .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                        long rawContactId = ContentUris.parseId(rawContactUri);
                                        long contactId = ContentUris.parseId(rawContactUri);

                                        values.clear();
                                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                contact.getString("telefono"));
                                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finderDialog.dismiss();
                                agregar[0] = false;
                            }
                        });
            }
        } else {
            LayoutInflater dialogInflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                    .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                    .setNegativeButton(R.string.add_contact_no, null);
            finderDialog = dialogBuilder.show();
            finderDialog.setCanceledOnTouchOutside(true);
            finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                finderDialog.dismiss();
                                agregar[0] = true;
                                if (agregar[0]) {
                                    ContentValues values = new ContentValues();
                                    values.put(ContactsContract.Data.DISPLAY_NAME, contact.getString("nombre"));
                                    Uri rawContactUri = contentResolver
                                            .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                    long rawContactId = ContentUris.parseId(rawContactUri);

                                    values.clear();
                                    values.put(android.provider.ContactsContract.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                            contact.getString("telefono"));
                                    values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(ContactsContract.Contacts.Data.MIMETYPE,
                                            ContactsContract.Data.CONTENT_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(ContactsContract.Contacts.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finderDialog.dismiss();
                            agregar[0] = false;
                        }
                    });
        }
        c.close();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

public void showDialogAddContact(final String contacto) {
    final boolean[] agregar = { false };
    try {/*from www. ja  v  a  2  s.  c om*/
        final ContentResolver contentResolver = activity.getContentResolver();
        final JSONObject contact = new JSONObject(contacto);
        String name = null;
        String phone = null;

        String selectionArgs = ContactsContract.Contacts.DISPLAY_NAME + " = ? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

        Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs,
                new String[] { contact.getString("nombre") }, null);

        if (c.getCount() > 0) {
            if (c.moveToFirst()) {
                phone = c.getString(0);
            }
            if (phone.equals(contact.getString("telefono"))) {
                Toast.makeText(activity, "Ya tienes este contacto", Toast.LENGTH_SHORT).show();
            } else {
                LayoutInflater dialogInflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                        .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                        .setNegativeButton(R.string.add_contact_no, null);
                finderDialog = dialogBuilder.show();
                finderDialog.setCanceledOnTouchOutside(true);
                finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    finderDialog.dismiss();
                                    agregar[0] = true;
                                    if (agregar[0]) {
                                        ContentValues values = new ContentValues();
                                        values.put(ContactsContract.Data.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        Uri rawContactUri = contentResolver
                                                .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                        long rawContactId = ContentUris.parseId(rawContactUri);
                                        long contactId = ContentUris.parseId(rawContactUri);

                                        values.clear();
                                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                contact.getString("telefono"));
                                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                        values.put(Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finderDialog.dismiss();
                                agregar[0] = false;
                            }
                        });
            }
        } else {
            LayoutInflater dialogInflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                    .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                    .setNegativeButton(R.string.add_contact_no, null);
            finderDialog = dialogBuilder.show();
            finderDialog.setCanceledOnTouchOutside(true);
            finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                finderDialog.dismiss();
                                agregar[0] = true;
                                if (agregar[0]) {
                                    ContentValues values = new ContentValues();
                                    values.put(ContactsContract.Data.DISPLAY_NAME, contact.getString("nombre"));
                                    Uri rawContactUri = contentResolver
                                            .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                    long rawContactId = ContentUris.parseId(rawContactUri);

                                    values.clear();
                                    values.put(android.provider.ContactsContract.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                            contact.getString("telefono"));
                                    values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(Data.MIMETYPE, ContactsContract.Data.CONTENT_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finderDialog.dismiss();
                            agregar[0] = false;
                        }
                    });
        }
        c.close();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}