Example usage for android.content ContentProviderClient query

List of usage examples for android.content ContentProviderClient query

Introduction

In this page you can find the example usage for android.content ContentProviderClient query.

Prototype

public @Nullable Cursor query(@NonNull Uri url, @Nullable String[] projection, @Nullable String selection,
        @Nullable String[] selectionArgs, @Nullable String sortOrder) throws RemoteException 

Source Link

Document

See ContentProvider#query ContentProvider.query

Usage

From source file:cn.edu.wyu.documentviewer.model.DocumentInfo.java

public void updateFromUri(ContentResolver resolver, Uri uri) throws FileNotFoundException {
    ContentProviderClient client = null;
    Cursor cursor = null;/*  w  w  w  . java2s.c om*/
    try {
        client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, uri.getAuthority());
        cursor = client.query(uri, null, null, null, null);
        if (!cursor.moveToFirst()) {
            throw new FileNotFoundException("Missing details for " + uri);
        }
        updateFromCursor(cursor, uri.getAuthority());
    } catch (Throwable t) {
        throw asFileNotFoundException(t);
    } finally {
        IOUtils.closeQuietly(cursor);
        ContentProviderClient.releaseQuietly(client);
    }
}

From source file:cn.edu.wyu.documentviewer.RootsCache.java

/**
 * Bring up requested provider and query for all active roots.
 *///from   ww w.  j a v a  2  s  .c  om
private Collection<RootInfo> loadRootsForAuthority(ContentResolver resolver, String authority) {
    if (DEBUG)
        Log.d(TAG, "Loading roots for " + authority);

    synchronized (mObservedAuthorities) {
        if (mObservedAuthorities.add(authority)) {
            // Watch for any future updates
            final Uri rootsUri = DocumentsContract.buildRootsUri(authority);
            mContext.getContentResolver().registerContentObserver(rootsUri, true, mObserver);
        }
    }

    final List<RootInfo> roots = Lists.newArrayList();
    final Uri rootsUri = DocumentsContract.buildRootsUri(authority);

    ContentProviderClient client = null;
    Cursor cursor = null;
    try {
        client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, authority);
        cursor = client.query(rootsUri, null, null, null, null);
        while (cursor.moveToNext()) {
            final RootInfo root = RootInfo.fromRootsCursor(authority, cursor);
            roots.add(root);
        }
    } catch (Exception e) {
        Log.w(TAG, "Failed to load some roots from " + authority + ": " + e);
    } finally {
        IOUtils.closeQuietly(cursor);
        ContentProviderClient.releaseQuietly(client);
    }
    return roots;
}

From source file:com.example.jumpnote.android.SyncAdapter.java

public List<ModelJava.Note> getLocallyChangedNotes(ContentProviderClient provider, Account account,
        Date sinceDate) throws RemoteException {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Getting local notes changed since " + Long.toString(sinceDate.getTime()));
    }/*  w w  w . jav a2s. com*/
    Cursor notesCursor = provider.query(JumpNoteContract.buildNoteListUri(account.name), PROJECTION,
            JumpNoteContract.Notes.MODIFIED_DATE + " > ?", new String[] { Long.toString(sinceDate.getTime()) },
            null);

    List<ModelJava.Note> locallyChangedNotes = new ArrayList<ModelJava.Note>();
    while (notesCursor.moveToNext()) {
        ContentValues values = new ContentValues();
        DatabaseUtils.cursorRowToContentValues(notesCursor, values);
        ModelJava.Note changedNote = new ModelJava.Note(values);
        locallyChangedNotes.add(changedNote);
    }

    notesCursor.close();
    return locallyChangedNotes;
}

From source file:com.samsung.android.remindme.SyncAdapter.java

public List<ModelJava.Alert> getLocallyChangedAlerts(ContentProviderClient provider, Account account,
        Date sinceDate) throws RemoteException {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Getting local alerts changed since " + Long.toString(sinceDate.getTime()));
    }/*w ww .j a v  a 2s .  com*/
    Cursor alertsCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION,
            RemindMeContract.Alerts.MODIFIED_DATE + " > ?", new String[] { Long.toString(sinceDate.getTime()) },
            null);

    List<ModelJava.Alert> locallyChangedAlerts = new ArrayList<ModelJava.Alert>();
    while (alertsCursor.moveToNext()) {
        ContentValues values = new ContentValues();
        DatabaseUtils.cursorRowToContentValues(alertsCursor, values);
        ModelJava.Alert changedAlert = new ModelJava.Alert(values);
        locallyChangedAlerts.add(changedAlert);
    }

    alertsCursor.close();
    return locallyChangedAlerts;
}

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

private boolean shouldSyncNow(Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException {
    Cursor c = null;/*from  www.  j a  v a 2 s . c  o m*/
    try {
        c = provider.query(GMSSyncs.CONTENT_URI, new String[] { GMSSync._ID, GMSSync.SYNC_DATE }, null, null,
                GMSSync.DEFAULT_SORT_ORDER);
        if (c == null) {
            syncResult.databaseError = true;
        } else if (c.getCount() == 0) {
            // Setup our group visibility on the very first sync
            GMSContactOperations.setAccountContactsVisibility(getContext(), account, true);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return true;
}

From source file:org.voidsink.anewjkuapp.calendar.CalendarUtils.java

private static boolean deleteKusssEvents(Context context, String calId) {
    if (calId != null) {
        ContentProviderClient provider = context.getContentResolver()
                .acquireContentProviderClient(CalendarContractWrapper.Events.CONTENT_URI());

        if (provider == null) {
            return false;
        }//from   w  w w.ja  va  2 s.co  m

        try {
            Uri calUri = CalendarContractWrapper.Events.CONTENT_URI();

            Cursor c = loadEvent(provider, calUri, calId);
            if (c != null) {
                try {
                    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
                    long deleteFrom = new Date().getTime() - DateUtils.DAY_IN_MILLIS;
                    while (c.moveToNext()) {
                        long eventDTStart = c.getLong(CalendarUtils.COLUMN_EVENT_DTSTART);
                        if (eventDTStart > deleteFrom) {
                            String eventId = c.getString(COLUMN_EVENT_ID);
                            //                        Log.d(TAG, "---------");
                            String eventKusssId = null;

                            // get kusssId from extended properties
                            Cursor c2 = provider.query(CalendarContract.ExtendedProperties.CONTENT_URI,
                                    CalendarUtils.EXTENDED_PROPERTIES_PROJECTION,
                                    CalendarContract.ExtendedProperties.EVENT_ID + " = ?",
                                    new String[] { eventId }, null);

                            if (c2 != null) {
                                while (c2.moveToNext()) {
                                    if (c2.getString(1).contains(EXTENDED_PROPERTY_NAME_KUSSS_ID)) {
                                        eventKusssId = c2.getString(2);
                                    }
                                }
                                c2.close();
                            }

                            if (TextUtils.isEmpty(eventKusssId)) {
                                eventKusssId = c.getString(COLUMN_EVENT_KUSSS_ID_LEGACY);
                            }

                            if (!TextUtils.isEmpty(eventKusssId)) {
                                if (eventKusssId.startsWith("at-jku-kusss-exam-")
                                        || eventKusssId.startsWith("at-jku-kusss-coursedate-")) {
                                    Uri deleteUri = calUri.buildUpon().appendPath(eventId).build();
                                    Log.d(TAG, "Scheduling delete: " + deleteUri);
                                    batch.add(ContentProviderOperation.newDelete(deleteUri).build());
                                }
                            }
                        }
                    }
                    if (batch.size() > 0) {
                        Log.d(TAG, "Applying batch update");
                        provider.applyBatch(batch);
                        Log.d(TAG, "Notify resolver");
                    } else {
                        Log.w(TAG, "No batch operations found! Do nothing");
                    }
                } catch (RemoteException | OperationApplicationException e) {
                    Analytics.sendException(context, e, true);
                    return false;
                }
            }
        } finally {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                provider.close();
            } else {
                provider.release();
            }
        }
        return false;
    }
    return true;
}

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

private void processDeletedGroups(ContentProviderClient provider, String authToken, Account account,
        SyncResult syncResult) throws RemoteException, ClientProtocolException, IOException, JSONException {
    Cursor cursor = null;//ww w  .j a  v  a  2s .  com
    try {
        cursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup.CLOUD_ID },
                GMSGroup.STATUS + "=?", new String[] { String.valueOf(GMSGroup.STATUS_DELETED) }, null);
        if (cursor == null) {
            syncResult.databaseError = true;
            return;
        }
        while (cursor.moveToNext()) {
            if (NetworkUtilities.deleteGroup(authToken, cursor.getString(0)) != null) {
                syncResult.stats.numDeletes++;
            } else {
                syncResult.stats.numIoExceptions++;
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

private void processDeletedContacts(ContentProviderClient provider, String authToken, Account account,
        SyncResult syncResult) throws IOException, JSONException, RemoteException {
    Cursor contactCursor = null;/*from  w  ww.  j  a v a2 s.  com*/
    try {
        contactCursor = provider.query(GMSContacts.CONTENT_URI,
                new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.STATUS, GMSContact.GROUP_ID },
                GMSContact.STATUS + "=?", new String[] { String.valueOf(GMSContact.STATUS_DELETED) }, null);
        if (contactCursor == null) {
            syncResult.databaseError = true;
            return;
        }
        while (contactCursor.moveToNext()) {
            Cursor groupCursor = null;
            try {
                groupCursor = provider.query(
                        ContentUris.withAppendedId(GMSGroups.CONTENT_URI, contactCursor.getLong(3)),
                        new String[] { GMSGroup.CLOUD_ID }, null, null, null);
                if (groupCursor == null || !groupCursor.moveToFirst()) {
                    syncResult.databaseError = true;
                    break;
                }
                if (NetworkUtilities.removeGroupContact(authToken, groupCursor.getString(0),
                        contactCursor.getString(1)) == null) {
                    syncResult.stats.numIoExceptions++;
                } else {
                    syncResult.stats.numDeletes++;
                }
            } finally {
                if (groupCursor != null) {
                    groupCursor.close();
                }
            }
        }
    } finally {
        if (contactCursor != null) {
            contactCursor.close();
        }
    }

}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

private boolean hasLocalChanges(ContentProviderClient provider, Uri changesUri) throws RemoteException {
    boolean result = false;
    Cursor c = provider.query(changesUri, new String[] { "count(*)" }, null, null, null);

    if (c != null) {
        if (c.moveToFirst()) {
            result = c.getLong(0) > 0;
        }// ww w. j av  a 2 s . c o m
        c.close();
    }
    return result;
}

From source file:org.ohmage.sync.OhmageSyncAdapter.java

private void synchronizeOhmlets(final String userId, ContentProviderClient provider)
        throws AuthenticationException, RemoteException, InterruptedException {
    Log.d(TAG, "state of ohmlets sync");

    final CountDownLatch upload;

    // First, sync ohmlet join state. As described by the people field.
    Cursor cursor = null;//w  ww  .  j a  v  a2 s.  c om
    try {
        cursor = provider.query(OhmageContract.Ohmlets.CONTENT_URI,
                new String[] { OhmageContract.Ohmlets.OHMLET_ID, OhmageContract.Ohmlets.OHMLET_MEMBERS },
                Ohmlets.OHMLET_DIRTY + "=1", null, null);

        upload = new CountDownLatch(cursor.getCount());

        while (cursor.moveToNext()) {
            Member.List members = gson.fromJson(cursor.getString(1), Member.List.class);
            Member m = members.getMember(userId);
            if (m == null) {
                m = members.getMember("me");
                if (m != null) {
                    m.memberId = userId;
                }
            }
            final Member localMember = m;
            ohmageService.getOhmlet(cursor.getString(0)).first(new Func1<Ohmlet, Boolean>() {
                @Override
                public Boolean call(Ohmlet ohmlet) {
                    Member remoteMember = ohmlet.people.getMember(userId);
                    try {
                        if (localMember != null) {
                            if (remoteMember == null || localMember.role != remoteMember.role) {
                                // Check for join verification code to send
                                if (localMember.code != null) {
                                    String code = localMember.code;
                                    localMember.code = null;
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember, code);
                                } else {
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember);
                                }
                            }
                        }
                        if (localMember == null && remoteMember != null) {
                            ohmageService.removeUserFromOhmlet(ohmlet.ohmletId, userId);
                        }
                    } catch (AuthenticationException e) {
                        Log.e(TAG, "Error authenticating user", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numAuthExceptions++;
                    } catch (RetrofitError e) {
                        Log.e(TAG, "Error synchronizing ohmlet member state", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numIoExceptions++;
                    }
                    return true;
                }
            }).finallyDo(new Action0() {
                @Override
                public void call() {
                    upload.countDown();
                }
            }).subscribe();
        }
        cursor.close();

        // Wait for the upload sync operation to finish before downloading the user state
        upload.await();

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}