Example usage for android.content ContentUris withAppendedId

List of usage examples for android.content ContentUris withAppendedId

Introduction

In this page you can find the example usage for android.content ContentUris withAppendedId.

Prototype

public static Uri withAppendedId(Uri contentUri, long id) 

Source Link

Document

Appends the given ID to the end of the path.

Usage

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static void updateContactPhotoHd(Context context, ContentResolver resolver, long rawContactId,
        ContactPhoto photo, BatchOperation batchOperation) {
    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION,
            Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
            new String[] { String.valueOf(rawContactId), Photo.CONTENT_ITEM_TYPE }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, true,
            batchOperation);// w  w  w .  j a va2s . co m

    if ((c != null) && c.moveToFirst()) {
        final long id = c.getLong(DataQuery.COLUMN_ID);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
        contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), photo.getPhotoUrl(), uri);
        c.close();
    } else {
        Log.i(TAG, "creating row, count: " + c.getCount());
        contactOp.addAvatar(photo.getPhotoUrl());
    }
    Log.d(TAG, "updating check timestamp");
    final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    contactOp.updateSyncTimestamp1(System.currentTimeMillis(), uri);
}

From source file:com.granita.tasks.TaskListFragment.java

private void selectChildView(ExpandableListView expandLV, int groupPosition, int childPosition, boolean force) {
    if (groupPosition < mAdapter.getGroupCount() && childPosition < mAdapter.getChildrenCount(groupPosition)) {
        // a task instance element has been clicked, get it's instance id and notify the activity
        ExpandableListAdapter listAdapter = expandLV.getExpandableListAdapter();
        Cursor cursor = (Cursor) listAdapter.getChild(groupPosition, childPosition);

        if (cursor == null) {
            return;
        }/* ww w  .j a  v  a 2 s . co m*/
        // TODO: for now we get the id of the task, not the instance, once we support recurrence we'll have to change that
        Long selectTaskId = cursor.getLong(cursor.getColumnIndex(Instances.TASK_ID));

        if (selectTaskId != null) {
            // Notify the active callbacks interface (the activity, if the fragment is attached to one) that an item has been selected.

            // TODO: use the instance URI one we support recurrence
            Uri taskUri = ContentUris.withAppendedId(Tasks.getContentUri(mAuthority), selectTaskId);

            mCallbacks.onItemSelected(taskUri, force, mInstancePosition);
        }
    }
}

From source file:com.fututel.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;//from  w w w . ja va  2s . co  m
    Uri baseInsertedUri = null;
    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.android.browser.BookmarksPageCallbacks.java

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    BrowserBookmarksAdapter adapter = getChildAdapter(groupPosition);
    Cursor cursor = adapter.getItem(childPosition);
    boolean isFolder = cursor.getInt(BookmarksLoader.COLUMN_INDEX_IS_FOLDER) != 0;
    if (mCallbacks != null && mCallbacks.onBookmarkSelected(cursor, isFolder)) {
        return true;
    }/* ww w .  j av  a  2 s .  c  o  m*/

    if (isFolder) {
        String title = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
        Uri uri = ContentUris.withAppendedId(BrowserContract.Bookmarks.CONTENT_URI_DEFAULT_FOLDER, id);
        BreadCrumbView crumbs = getBreadCrumbs(groupPosition);
        if (crumbs != null) {
            // update crumbs
            crumbs.pushView(title, uri);
            crumbs.setVisibility(View.VISIBLE);
        }
        loadFolder(groupPosition, uri);
    }
    return true;
}

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

/**
 * We know that the group exists locally, so we can use the data in the JSON group as gold
 * @param group/*from  w ww  .  j  av a 2s . c o m*/
 * @param provider
 * @param authToken
 * @param account
 * @param syncResult
 * @throws JSONException
 * @throws RemoteException
 * @throws OperationApplicationException
 */
private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider,
        String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException {

    if (!group.has(JSONKeys.KEY_MEMBERS)) {
        return;
    }
    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID },
            GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null);
    try {
        if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) {
            syncResult.databaseError = true;
            return;
        }
        long groupId = groupCursor.getLong(0);
        if (groupId < 0L) {
            syncResult.databaseError = true;
            return;
        }
        // Optimistically add the contacts
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        for (int j = 0; j < membersArray.length(); ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // If the first operation asserts it means the contact exists already
            // Operation 0
            ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI)
                    .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) })
                    .withExpectedCount(0).build();
            ops.add(op);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI)
                    .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build();
            ops.add(op);
            try {
                @SuppressWarnings("unused")
                ContentProviderResult[] results = provider.applyBatch(ops);
            } catch (OperationApplicationException e) {
                // The contact already exists, so we'll optionally update it, based on its version
                Cursor contactCursor = null;
                try {
                    contactCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID },
                            GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null);
                    if (contactCursor == null || !contactCursor.moveToFirst()) {
                        syncResult.databaseError = true;
                        return;
                    }
                    // The member already exists, so optinally update it
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists. If its the right version, we don't need to do the update
                    // So we assert that we'll find zero records with the current version and if that's right, we'll update our
                    // record, including the version with the new record data
                    op = ContentProviderOperation
                            .newAssertQuery(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withSelection(GMSContact.VERSION + "=?",
                                    new String[] { member.getString(JSONKeys.KEY_VERSION) })
                            .withExpectedCount(0).build();
                    ops.add(op);
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValues(GMSApplication.getMemberValues(member))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    provider.applyBatch(ops);
                } catch (OperationApplicationException l) {
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed
                    // We still have to update the status to SYNCED so we don't blow it away later.
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    try {
                        provider.applyBatch(ops);
                    } catch (OperationApplicationException e1) {
                        syncResult.stats.numSkippedEntries++;
                        e1.printStackTrace();
                    }
                } finally {
                    if (contactCursor != null) {
                        contactCursor.close();
                    }
                }
            }
        }
    } finally {
        if (groupCursor != null) {
            groupCursor.close();
        }
    }
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

private void getServerPhotos(SyncContext context, String feedUrl, int maxDownloads, GDataSyncData syncData,
        SyncResult syncResult) {//  w ww  .j  a  v  a 2  s. c o m
    final ContentResolver cr = getContext().getContentResolver();
    Cursor cursor = cr.query(Photos.CONTENT_URI,
            new String[] { Photos._SYNC_ID, Photos._SYNC_VERSION, Photos.PERSON_ID, Photos.DOWNLOAD_REQUIRED,
                    Photos._ID },
            "" + "_sync_account=? AND download_required != 0", new String[] { getAccount() }, null);
    try {
        int numFetched = 0;
        while (cursor.moveToNext()) {
            if (numFetched >= maxDownloads) {
                break;
            }
            String photoSyncId = cursor.getString(0);
            String photoVersion = cursor.getString(1);
            long person = cursor.getLong(2);
            String photoUrl = feedUrl + "/" + photoSyncId;
            long photoId = cursor.getLong(4);

            try {
                context.setStatusText("Downloading photo " + photoSyncId);
                ++numFetched;
                ++mPhotoDownloads;
                InputStream inputStream = mContactsClient.getMediaEntryAsStream(photoUrl, getAuthToken());
                savePhoto(person, inputStream, photoVersion);
                syncResult.stats.numUpdates++;
            } catch (IOException e) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.d(TAG, "error downloading " + photoUrl, e);
                }
                syncResult.stats.numIoExceptions++;
                return;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (Config.LOGD) {
                        Log.d(TAG, "not authorized to download " + photoUrl, e);
                    }
                    syncResult.stats.numAuthExceptions++;
                    return;
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                    final String exceptionMessage = e.getMessage();
                    if (Config.LOGD) {
                        Log.d(TAG, "unable to download photo " + photoUrl + ", " + exceptionMessage
                                + ", ignoring");
                    }
                    ContentValues values = new ContentValues();
                    values.put(Photos.SYNC_ERROR, exceptionMessage);
                    Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(People.CONTENT_URI, photoId),
                            Photos.CONTENT_DIRECTORY);
                    cr.update(photoUri, values, null /* where */, null /* where args */);
                    break;
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error downloading " + photoUrl, e);
                    }
                    syncResult.stats.numIoExceptions++;
                    return;
                }
            }
        }
        final boolean hasMoreToSync = numFetched < cursor.getCount();
        GDataSyncData.FeedData feedData = new GDataSyncData.FeedData(0 /* no update time */, numFetched,
                hasMoreToSync, null /* no lastId */, 0 /* no feed index */);
        syncData.feedData.put(feedUrl, feedData);
    } finally {
        cursor.close();
    }
}

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 a  v  a 2s. com
 * 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:com.bangz.smartmute.services.LocationMuteService.java

private void handleGeofenceTrigger(Intent intent) {

    LogUtils.LOGD(TAG, "Handling Geofence trigger ...");
    HashMap<Integer, String> mapRingerMode = new HashMap<Integer, String>();
    mapRingerMode.put(AudioManager.RINGER_MODE_NORMAL, "Normal");
    mapRingerMode.put(AudioManager.RINGER_MODE_SILENT, "Silent");
    mapRingerMode.put(AudioManager.RINGER_MODE_VIBRATE, "Vibrate");

    HashMap<Integer, String> mapTransition = new HashMap<Integer, String>();
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_DWELL, "DWELL");
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_ENTER, "ENTER");
    mapTransition.put(Geofence.GEOFENCE_TRANSITION_EXIT, "EXIT");

    GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);

    if (geoEvent.hasError() == false) {
        LogUtils.LOGD(TAG, "\tgeoEvent has no error.");
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager == null) {
            LogUtils.LOGD(TAG, "\t !!!!!  AudioManager == null !!!!!!!");
            return;
        }/*  ww  w.  j a v  a  2  s  . c  o m*/
        int currringermode = audioManager.getRingerMode();

        List<Geofence> geofences = geoEvent.getTriggeringGeofences();

        int transition = geoEvent.getGeofenceTransition();
        ContentResolver cr = getContentResolver();

        //int enterTransition = Config.TEST_BUILD ? Geofence.GEOFENCE_TRANSITION_ENTER : Geofence.GEOFENCE_TRANSITION_DWELL;
        LogUtils.LOGD(TAG, "\tTransition: " + mapTransition.get(transition));
        if (transition == Geofence.GEOFENCE_TRANSITION_DWELL
                || transition == Geofence.GEOFENCE_TRANSITION_ENTER) {

            boolean setted = false;
            for (Geofence geofence : geofences) {
                long id = Long.parseLong(geofence.getRequestId());
                Uri uri = ContentUris.withAppendedId(RulesColumns.CONTENT_ID_URI_BASE, id);
                Cursor cursor = cr.query(uri, PROJECTS, RulesColumns.ACTIVATED + " = 1", null, null);

                if (cursor.getCount() != 0) {
                    cursor.moveToFirst();
                    int setmode = cursor.getInt(cursor.getColumnIndex(RulesColumns.RINGMODE));

                    if (currringermode == setmode) {
                        LogUtils.LOGD(TAG, "\tringer mode already is in silent or vibrate. we do nothing");
                    } else {

                        LogUtils.LOGD(TAG, "\tset ringer mode to " + setmode);
                        audioManager.setRingerMode(setmode);
                        PrefUtils.rememberWhoMuted(this, id);
                        //TODO Notify to user ?
                    }
                    setted = true;

                } else {
                    LogUtils.LOGD(TAG,
                            "\tid = " + id + " trigger, but does not find in database. maybe disabled.");
                }

                cursor.close();
                cursor = null;

                if (setted == true) {
                    break;
                }
            }
        } else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            for (Geofence geofence : geofences) {
                long id = Long.parseLong(geofence.getRequestId());
                if (id == PrefUtils.getLastSetMuteId(this)) {
                    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                    if (am != null) {
                        am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    }
                    PrefUtils.cleanLastMuteId(this);
                    break;
                }
            }
        } else {
            LogUtils.LOGD(TAG, "transition is " + transition + " ; != entertransition && !! EXIT");
        }

    } else {
        PrefUtils.Geofencing(this, false);
        if (geoEvent.getErrorCode() == GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE) {

            NotificationUserFailed();

            ReceUtils.enableReceiver(this, LocationProviderChangedReceiver.class, true);
        } else {
            LogUtils.LOGD(TAG, "\tHandle Geofence trigger error. errcode = " + geoEvent.getErrorCode());
        }
    }

    LogUtils.LOGD(TAG, "Successful Leave handling Geofence trigger.");
}

From source file:com.appsimobile.appsii.module.home.provider.HomeContentProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {

    SqlArguments args = new SqlArguments(uri);

    checkInsertConstraints(args.table, initialValues);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final long rowId = db.insert(args.table, null, initialValues);
    if (rowId <= 0)
        return null;

    uri = ContentUris.withAppendedId(uri, rowId);
    sendNotify(uri);//ww  w .j a v  a  2s. co  m

    return uri;
}

From source file:com.akop.bach.fragment.xboxlive.MessagesFragment.java

@Override
public void onImageReady(long id, Object param, Bitmap bmp) {
    super.onImageReady(id, param, bmp);

    if (getActivity() != null) {
        getActivity().getContentResolver().notifyChange(ContentUris.withAppendedId(Messages.CONTENT_URI, id),
                null);/*  w w  w  . j av  a 2 s  . c o  m*/
    }
}