Example usage for android.database Cursor setNotificationUri

List of usage examples for android.database Cursor setNotificationUri

Introduction

In this page you can find the example usage for android.database Cursor setNotificationUri.

Prototype

void setNotificationUri(ContentResolver cr, Uri uri);

Source Link

Document

Register to watch a content URI for changes.

Usage

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private Cursor queryArtwork(@NonNull final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    ContentResolver contentResolver = getContext() != null ? getContext().getContentResolver() : null;
    if (contentResolver == null) {
        return null;
    }//from w  ww.  j  av  a 2s .  co m
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Artwork.TABLE_NAME + " INNER JOIN " + MuzeiContract.Sources.TABLE_NAME + " ON "
            + MuzeiContract.Artwork.TABLE_NAME + "." + MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME
            + "=" + MuzeiContract.Sources.TABLE_NAME + "." + MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME);
    qb.setProjectionMap(allArtworkColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <artworkId>"
        // to the where clause, so that it selects that single piece of artwork
        qb.appendWhere(
                MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED + " DESC, "
                + MuzeiContract.Artwork.DEFAULT_SORT_ORDER;
    else
        orderBy = sortOrder;
    final Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null);
    c.setNotificationUri(contentResolver, uri);
    return c;
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final int code = contentHelper.matchUri(uri);
    if (code != UriMatcher.NO_MATCH) {
        if (code == ContentHelper.uriSyncCode) {
            return null;
        }//from   www  .  ja  v a 2 s .  co m
        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode);
        builder.setTables(tab.name);
        if (isItemCode(code)) {
            if (isItemRowIDCode(code)) {
                selection = "isDeleted=0 AND ROWID=" + uri.getPathSegments().get(2)
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
            } else {
                selection = "isDeleted=0" + tab.getSelection()
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
                int i = 0;
                final String[] old = selectionArgs;
                final int len = (old == null) ? 0 : old.length;
                selectionArgs = new String[len + tab.primaryKey.length];
                for (; i < tab.primaryKey.length; i++) {
                    selectionArgs[i] = uri.getPathSegments().get(i + 1);
                }
                if (len > 0) {
                    for (; i < old.length; i++) {
                        selectionArgs[i] = old[i - tab.primaryKey.length];
                    }
                }
            }
        } else {
            selection = "isDeleted=0" + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
        }
        builder.setProjectionMap(tab.map);

        Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, null, null,
                sortOrder);
        if (DEBUG) {
            Log.d("Query",
                    builder.buildQuery(projection, selection, selectionArgs, null, null, sortOrder, null));
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
    throw new IllegalArgumentException("Unknown Uri " + uri);
}

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

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    selection = fixWhereProjection(uri, selection);
    SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String tables = createTablesFromTableQuery(args.table);

    qb.setTables(tables);/*from  www .  ja v  a2  s  .c  o  m*/

    Map<String, String> projectionMap = getProjectionMapForTable(args.table);

    if (projectionMap != null) {
        qb.setProjectionMap(projectionMap);
        qb.setStrict(true);
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    if (HomeContract.CELLS_TABLE_NAME.equals(args.table)) {
        sortOrder = fixSortOrder(sortOrder);
    }
    String where = args.where;
    if (HomeContract.HOTSPOT_PAGES_DETAILS_TABLE_NAME.equals(args.table)) {
        where = "_ht." + BaseColumns._ID + "=" + ContentUris.parseId(uri);
    }

    Cursor result = qb.query(db, projection, where, args.args, null, null, sortOrder);

    result.setNotificationUri(getContext().getContentResolver(), uri);

    return result;
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getWritableDatabase();
    String tableName;// w w  w .  j  a v a2 s. c  o m
    String where;
    String order = "";
    Bundle bundleSyncAdapter = new Bundle();
    String lastPathSegment = uri.getLastPathSegment();

    if (StringUtils.isNotBlank(sortOrder)) {
        order = " ORDER BY " + sortOrder;
    }

    switch (URI_MATCHER.match(uri)) {

    // Getting the content for a group (list of simple data)
    case CatalogContract.Provider.CODE_GROUP_ID:
        tableName = CatalogContract.DataBaseDataSimple.TABLE_NAME;
        where = CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + "."
                + CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "='" + lastPathSegment + "'";

        // Limit for the query on the sync adapter
        String currentPage = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_CURRENT_PAGE);
        String pageSize = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_PAGE_SIZE);

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, lastPathSegment);

        if (StringUtils.isNotBlank(currentPage) && StringUtils.isNotBlank(pageSize)) {
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE,
                    Integer.valueOf(currentPage));
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, Integer.valueOf(pageSize));
        }

        break;

    // Getting a specific data detail
    case CatalogContract.Provider.CODE_DATA_ID:
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        tableName = CatalogContract.DataBaseDataDetails.TABLE_NAME;
        where = CatalogContract.DataBaseDataDetails.TABLE_NAME + "."
                + CatalogContract.DataBaseDataDetails.ATT_DATA_ID + "='" + lastPathSegment + "'";

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_DATA_ID, lastPathSegment);

        // We don't load the variants for a specific data
        bundleSyncAdapter.putBoolean(CatalogSyncConstants.SYNC_PARAM_LOAD_VARIANTS, false);
        break;

    default:
        Log.e(TAG, "URI not recognized" + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());

    }

    // We do the query by joining the data to the group
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + tableName + " INNER JOIN "
            + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + " ON " + tableName + "."
            + CatalogContract.DataBaseData.ATT_DATA_ID + "=" + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME
            + "." + CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID + " WHERE " + where + order, null);

    // Register the cursor to watch the uri for changes
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    // Existing data
    if (cursor.getCount() > 0) {
        // TODO - For now we check if one the items is out-of-sync and we sync all of them if this is the case
        // Future - Check every out-of-date items and sync them
        cursor.moveToLast();
        int status = cursor.getInt(cursor.getColumnIndex(CatalogContract.DataBaseData.ATT_STATUS));
        cursor.moveToFirst();

        // Data expired, we request a sync
        if (status == CatalogContract.SyncStatus.OUTOFDATE.getValue()) {
            Log.i(TAG, "Data for " + uri.toString() + " is out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);

            // TODO - the uptodate/outofdate should be done in the sync adapter
            // We up-to-date all the data in case the sync does not return any results (we base our out of sync on the last item of the cursor)
            if (URI_MATCHER.match(uri) == CatalogContract.Provider.CODE_GROUP_ID) {
                updateInternalDataSyncStatus(cursor, tableName, SyncStatus.UPTODATE);
            }
        }
        // Data updated, we invalidate the data
        else {
            Log.i(TAG, "Data for " + uri.toString() + " is up-of-date, invalidating it");
            updateInternalDataSyncStatus(cursor, tableName, SyncStatus.OUTOFDATE);
        }

    }
    // No data found, we request a sync if it's not already up-to-date
    else {
        boolean triggerSyncAdapter;

        switch (URI_MATCHER.match(uri)) {

        // Saving the sync info for the group
        case CatalogContract.Provider.CODE_GROUP_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriSyncGroup(authority),
                    CatalogContract.DataBaseSyncStatusGroup.ATT_GROUP_ID,
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, lastPathSegment);

            break;

        // Saving the sync info for the data
        case CatalogContract.Provider.CODE_DATA_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriData(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataSimple.TABLE_NAME,
                    lastPathSegment);
            break;

        // Saving the sync info for the data details
        case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriDataDetails(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataDetails.TABLE_NAME,
                    lastPathSegment);
            break;

        default:
            Log.e(TAG, "URI not recognized" + uri.toString());
            throw new IllegalArgumentException("URI not recognized" + uri.toString());

        }

        // Trigger the sync adapter
        if (triggerSyncAdapter) {
            Log.i(TAG, "No data found for " + uri.toString() + " and data out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);
        } else {
            Log.i(TAG, "No data found for " + uri.toString() + " and data up-to-date");
        }

    }

    return cursor;
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

private void setNotificationUri(final Cursor c, final Uri uri) {
    final ContentResolver cr = getContentResolver();
    if (cr == null || c == null || uri == null)
        return;//from  w ww  .j a  v  a2 s .c  om
    c.setNotificationUri(cr, uri);
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    Cursor cursor = null;
    switch (mUriMatcher.match(uri)) {
    case EXAMS:/*from  w  w  w.ja  va 2  s .c o  m*/
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(mOpenHelper.getTableName());
        qb.setProjectionMap(examsProjectionMap);
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        try {
            cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d(TAG, "SqlError: " + e.getMessage());
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        break;
    case EXAMS_UPDATE:
        MatrixCursor cur = new MatrixCursor(EXAMS_UPDATE_COLUMNS);
        Integer[] columnValues = updateGrades();
        cur.addRow(new Object[] { 0, columnValues[0], columnValues[1] });
        return cur;
    case EXAMINFOS:
        cursor = getExamInfos(selectionArgs[0], selectionArgs[1], false);
        break;
    case CERTIFICATIONS:
        cursor = getCertifications();
        break;
    default:
        throw new IllegalArgumentException("Unbekannte URI " + uri);
    }

    return cursor;
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf log = WebLogger.getLogger(pf.appName);

    // Get the database and run the query
    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;//from  w  ww.j a  v a 2  s.  co  m
    boolean success = false;
    Cursor c = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null,
                sortOrder, null);

        if (c == null) {
            log.w(t, "Unable to query database");
            return null;
        }
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        c.registerDataSetObserver(new InvalidateMonitor(pf.appName, dbHandleName));
        success = true;
        return c;
    } catch (Exception e) {
        log.w(t, "Exception while querying database");
        log.printStackTrace(e);
        return null;
    } finally {
        if (db != null) {
            try {
                db.releaseReference();
            } finally {
                if (!success) {
                    // this closes the connection
                    // if it was successful, then the InvalidateMonitor will close the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }/*from  w  w w . ja  v  a  2  s  . c om*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    // Get the database and run the query
    SQLiteDatabase db = null;
    boolean success = false;
    Cursor c = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, whereId, whereIdArgs, null, null,
                sortOrder);
        success = true;
    } catch (Exception e) {
        log.w(t, "Unable to query database for appName: " + appName);
        return null;
    } finally {
        if (!success && db != null) {
            db.close();
        }
    }

    if (c == null) {
        log.w(t, "Unable to query database for appName: " + appName);
        return null;
    }
    // Tell the cursor what uri to watch, so it knows when its source data
    // changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:org.kontalk.provider.UsersProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {/*from   w w w.j  av  a2  s . c  om*/
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    boolean offline = Boolean.parseBoolean(uri.getQueryParameter(Users.OFFLINE));

    int match = sUriMatcher.match(uri);
    if (match == USERS || match == USERS_JID) {
        // use the same table name as an alias
        String table = offline ? (TABLE_USERS_OFFLINE + " " + TABLE_USERS) : TABLE_USERS;
        qb.setTables(table);
        qb.setProjectionMap(usersProjectionMap);
    } else if (match == KEYS || match == KEYS_JID || match == KEYS_JID_FINGERPRINT) {
        qb.setTables(TABLE_KEYS);
        qb.setProjectionMap(keysProjectionMap);
    }

    switch (match) {
    case USERS:
        // nothing to do
        break;

    case USERS_JID: {
        // TODO append to selection
        String userId = uri.getPathSegments().get(1);
        selection = TABLE_USERS + "." + Users.JID + " = ?";
        selectionArgs = new String[] { userId };
        break;
    }

    case KEYS:
        // nothing to do
        break;

    case KEYS_JID:
    case KEYS_JID_FINGERPRINT:
        String userId = uri.getPathSegments().get(1);
        selection = DatabaseUtilsCompat.concatenateWhere(selection, Keys.JID + "=?");
        selectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { userId });
        // TODO support for fingerprint in Uri
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    if ((match == USERS || match == USERS_JID) && c.getCount() == 0
            && (match != USERS_JID || !XMPPUtils.isDomainJID(uri.getPathSegments().get(1)))) {
        // empty result set and sync requested
        SyncAdapter.requestSync(getContext(), false);
    }
    if (Boolean.parseBoolean(uri.getQueryParameter(Users.EXTRA_INDEX)) && c.getCount() > 0) {
        UsersCursor uc = new UsersCursor(c);
        bundleFastScrollingIndexExtras(uc, uri, db, qb, selection, selectionArgs, sortOrder, null);
        c = uc;
    }

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:com.money.manager.ex.MmxContentProvider.java

private Cursor query_internal(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {/*from w w w.java 2s.  c  o  m*/
    Timber.d("Querying URI: %s", uri);

    // find object from uri
    Object sourceObject = getObjectFromUri(uri);

    initializeDependencies();

    SQLiteDatabase database = openHelper.get().getReadableDatabase();
    if (database == null) {
        Timber.e("Database could not be opened");
        return null;
    }

    Cursor cursor;

    // check type of instance data set
    if (Dataset.class.isInstance(sourceObject)) {
        Dataset dataset = ((Dataset) sourceObject);

        //            logQuery(dataset, projection, selection, selectionArgs, sortOrder);

        switch (dataset.getType()) {
        case QUERY:
            String query = prepareQuery(dataset.getSource(), projection, selection, sortOrder);
            cursor = database.rawQuery(query, selectionArgs);
            break;
        case SQL:
            cursor = database.rawQuery(selection, selectionArgs);
            break;
        case TABLE:
        case VIEW:
            SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
            queryBuilder.setTables(dataset.getSource());
            cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Type of dataset not defined");
        }
    } else {
        throw new IllegalArgumentException("Object sourceObject of mapContent is not instance of dataset");
    }

    // notify listeners waiting for the data is ready
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    if (!cursor.isClosed()) {
        Timber.d("Rows returned: %d", cursor.getCount());
    }

    return cursor;
}