Example usage for android.content ContentResolver query

List of usage examples for android.content ContentResolver query

Introduction

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

Prototype

public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection,
        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) 

Source Link

Document

Query the given URI, returning a Cursor over the result set.

Usage

From source file:com.manning.androidhacks.hack023.dao.TodoDAO.java

private List<Todo> getTodosWithSelection(ContentResolver contentResolver, String selection) {
    Cursor cursor = contentResolver.query(TodoContentProvider.CONTENT_URI, null, selection, null, null);

    List<Todo> list = new ArrayList<Todo>();

    while (cursor.moveToNext()) {
        int localId = cursor.getInt(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_ID));
        int serverId = cursor.getInt(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_SERVER_ID));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_TITLE));
        int status = cursor.getInt(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_STATUS_FLAG));

        Todo currentTodo = new Todo();

        if (status == StatusFlag.ADD) {
            currentTodo.setId((long) localId);
        } else {/*  w ww .  ja  v  a  2 s . c o  m*/
            currentTodo.setId((long) serverId);
        }
        currentTodo.setTitle(name);
        currentTodo.setStatus(status);

        list.add(currentTodo);
    }

    cursor.close();
    return list;
}

From source file:com.remobile.file.ContentFilesystem.java

protected Cursor openCursorForURL(Uri nativeUri) {
    ContentResolver contentResolver = context.getContentResolver();
    try {/*w  w  w.ja v  a2  s  .  com*/
        return contentResolver.query(nativeUri, null, null, null, null);
    } catch (UnsupportedOperationException e) {
        return null;
    }
}

From source file:com.manning.androidhacks.hack023.dao.TodoDAO.java

public Todo isTodoInDb(ContentResolver contentResolver, Long serverId) {
    Todo todo = null;//from   ww  w  . j  a  v  a  2s. c  o  m

    Cursor cursor = contentResolver.query(TodoContentProvider.CONTENT_URI, null,
            TodoContentProvider.COLUMN_SERVER_ID + "=" + serverId, null, null);

    if (cursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_TITLE));
        int status = cursor.getInt(cursor.getColumnIndexOrThrow(TodoContentProvider.COLUMN_STATUS_FLAG));

        todo = new Todo();
        todo.setId(serverId);
        todo.setTitle(name);
        todo.setStatus(status);
    }

    cursor.close();
    return todo;
}

From source file:com.mobilesolutionworks.android.httpcache.HttpCacheLoaderImpl.java

public HttpCache onForceLoad(ContentObserver observer) {
    HttpCache tag = new HttpCache();
    tag.local = mBuilder.localUri();/*  ww w  .  j a v a2 s.  c  om*/

    Uri authority = HttpCacheConfiguration.configure(mContext).authority;

    ContentResolver cr = mContext.getContentResolver();
    tag.cursor = cr.query(authority, PROJECTION, "local = ?", new String[] { tag.local }, null);
    if (tag.cursor == null) {
        // cursor only null if provider is not set
        throw new IllegalStateException("is tag provider set properly?");
    }

    tag.cursor.getCount();
    tag.cursor.registerContentObserver(observer);
    tag.cursor.setNotificationUri(mContext.getContentResolver(),
            authority.buildUpon().appendEncodedPath(tag.local).build());

    if (tag.cursor.moveToFirst()) {
        // cache stored in database
        tag.loaded = true;
        tag.remote = tag.cursor.getString(0);
        tag.content = tag.cursor.getString(1);
        tag.expiry = tag.cursor.getLong(2);
        tag.error = tag.cursor.getInt(3);

        byte[] trace = tag.cursor.getBlob(4);
        if (trace != null) {
            tag.trace = SerializationUtils.deserialize(trace);
        }

        tag.status = tag.cursor.getInt(5);
    }

    return tag;
}

From source file:com.vedant.hereami.chatfolder.MyFirebaseMessagingService.java

public String getContactDisplayNameByNumber(String number) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String name = "?";

    ContentResolver contentResolver = getContentResolver();
    Cursor contactLookup = contentResolver.query(uri,
            new String[] { BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);

    try {/*  w ww.j ava2  s .com*/
        if (contactLookup != null && contactLookup.getCount() > 0) {
            contactLookup.moveToNext();
            name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
            //String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
            hashMap.put(name, number);
        }
    } finally {
        if (contactLookup != null) {
            contactLookup.close();
        }
    }

    return name;
}

From source file:com.sudhirkhanger.app.popularmovies.MainFragment.java

private void getDataFromDB() {
    mMovieArrayList = new ArrayList<>();
    ContentResolver resolver = getActivity().getContentResolver();
    Cursor cursor = resolver.query(MovieContract.MovieEntry.CONTENT_URI, null, null, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {//from  w ww  .j a v a2s. c  o  m
                String title = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.TITLE));
                String movie_id = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.MOVIE_ID));
                String poster = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.POSTER));
                String backdrop = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.BACKDROP));
                String overview = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.OVERVIEW));
                String vote_average = cursor
                        .getString(cursor.getColumnIndex(MovieContract.MovieEntry.VOTE_AVERAGE));
                String release_date = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.DATE));

                Movie movie = new Movie(title, release_date, poster, vote_average, overview, backdrop,
                        movie_id);
                mMovieArrayList.add(movie);
            } while (cursor.moveToNext());
        }
    }

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

From source file:com.almalence.googsharing.Thumbnail.java

private static Media getLastVideoThumbnail(ContentResolver resolver) {

    Media internalMedia = null;/*from  w w  w.j  a  v a 2  s  . co m*/
    Media externalMedia = null;

    String name = getName();

    try {
        Uri baseUri = Video.Media.INTERNAL_CONTENT_URI;

        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { VideoColumns._ID, VideoColumns.DATA, VideoColumns.DATE_TAKEN };

        String selection = VideoColumns.DATA + " like '%" + name + "%' AND " + VideoColumns.MIME_TYPE
                + "='video/mp4'";
        String order = VideoColumns.DATE_TAKEN + " DESC," + VideoColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                internalMedia = new Media(id, 0, cursor.getLong(2), ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    try {
        Uri baseUri = Video.Media.EXTERNAL_CONTENT_URI;
        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { VideoColumns._ID, VideoColumns.DATA, VideoColumns.DATE_TAKEN };

        String selection = VideoColumns.DATA + " like '%" + name + "%' AND " + VideoColumns.MIME_TYPE
                + "='video/mp4'";
        String order = VideoColumns.DATE_TAKEN + " DESC," + VideoColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                externalMedia = new Media(id, 0, cursor.getLong(2), ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    if (internalMedia == null) {
        return externalMedia;
    } else if (externalMedia == null) {
        return internalMedia;
    } else {
        return internalMedia.dateTaken > externalMedia.dateTaken ? internalMedia : externalMedia;
    }
}

From source file:com.jaspersoft.android.jaspermobile.util.ProfileHelper.java

public void seedProfilesIfNeed() {
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
            new String[] { ServerProfilesTable._ID }, null, null, null);
    if (cursor != null) {
        try {/*from  w  ww. j a  v a  2  s  . c  o  m*/
            if (cursor.getCount() == 0) {
                ServerProfiles testProfile = new ServerProfiles();

                testProfile.setAlias(DEFAULT_ALIAS);
                testProfile.setServerUrl(DEFAULT_SERVER_URL);
                testProfile.setOrganization(DEFAULT_ORGANIZATION);
                testProfile.setUsername(DEFAULT_USERNAME);
                testProfile.setPassword(DEFAULT_PASS);

                contentResolver.insert(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
                        testProfile.getContentValues());
                populateTestInstances(contentResolver);
            }
        } finally {
            cursor.close();
        }
    }
}

From source file:com.conferenceengineer.android.iosched.service.SessionAlarmService.java

private void scheduleAllStarredBlocks() {
    final ContentResolver cr = getContentResolver();
    final Cursor c = cr.query(
            ScheduleContract.Sessions.CONTENT_STARRED_URI, new String[] {
                    "distinct " + ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END },
            null, null, null);//from  w  w w  . j  av  a2  s.c  o m
    if (c == null) {
        return;
    }

    while (c.moveToNext()) {
        final long sessionStart = c.getLong(0);
        final long sessionEnd = c.getLong(1);
        scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
    }
}

From source file:com.amarinfingroup.net.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata/*from   w ww.ja v a  2 s .  com*/
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}