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:Main.java

final static public String GetContactNameByID(long contact_id, ContentResolver resolver) {
    if (resolver != null) {
        final Uri uri = Data.CONTENT_URI;

        final String[] columns = { ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
                ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME
                //,ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME
                /*Data._ID,*/
                //Data.CONTACT_ID, 
                //Data.LOOKUP_KEY
        };//from   www . j a  va 2  s.c  o  m
        final String where = Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
                + StructuredName.CONTENT_ITEM_TYPE + "'";
        final String[] where_arg = { String.valueOf(contact_id) };

        Cursor cur = resolver.query(uri, columns, where, where_arg, null);
        if (cur.moveToFirst()) {
            String result = "";
            final String family_name = cur.getString(0);
            if (family_name != null)
                result += family_name;
            final String given_name = cur.getString(1);
            if (given_name != null)
                result += " " + given_name;
            final String middle_name = cur.getString(2);
            if (middle_name != null)
                result += " " + middle_name;
            //return String.format("%s %s %s",family_name,given_name,middle_name);
            return result;
        } //if(cur.moveToFirst())
    } //if(resolver!=null)
    return null;
}

From source file:Main.java

/**
 * Retourner le nom de calendrier//from  www.  j a v  a 2 s.  c om
 * 
 * @param id
 * @return
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static String getCalendarName(ContentResolver contentResolver, String id) {
    String name = null;
    Cursor cursor;
    String[] projection;
    Uri calendarUri;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        calendarUri = CalendarContract.Calendars.CONTENT_URI;
        projection = new String[] { CalendarContract.Calendars._ID,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME };
    } else if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
        calendarUri = Uri.parse("content://com.android.calendar/calendars");
        projection = new String[] { "_id", "displayname" };
    } else {
        calendarUri = Uri.parse("content://calendar/calendars");
        projection = new String[] { "_id", "displayname" };
    }

    cursor = contentResolver.query(calendarUri, projection, "_id = ?", new String[] { id }, null);

    if (cursor.moveToFirst()) {
        name = cursor.getString(1);
    }

    cursor.close();

    return name;
}

From source file:com.indeema.email.NotificationController.java

private static void refreshNotificationsForAccountInternal(final Context context, final long accountId) {
    final ContentResolver contentResolver = context.getContentResolver();

    final Cursor accountCursor = contentResolver.query(EmailProvider.uiUri("uiaccount", accountId),
            UIProvider.ACCOUNTS_PROJECTION, null, null, null);

    if (accountCursor == null) {
        LogUtils.e(LOG_TAG, "Null account cursor for account id %d", accountId);
        return;//from  w  w  w.jav a 2  s.c om
    }

    com.indeema.mail.providers.Account account = null;
    try {
        if (accountCursor.moveToFirst()) {
            account = new com.indeema.mail.providers.Account(accountCursor);
        }
    } finally {
        accountCursor.close();
    }

    if (account == null) {
        LogUtils.d(LOG_TAG, "Tried to create a notification for a missing account %d", accountId);
        return;
    }

    final Cursor mailboxCursor = contentResolver.query(
            ContentUris.withAppendedId(EmailContent.MAILBOX_NOTIFICATION_URI, accountId), null, null, null,
            null);
    try {
        while (mailboxCursor.moveToNext()) {
            final long mailboxId = mailboxCursor.getLong(EmailContent.NOTIFICATION_MAILBOX_ID_COLUMN);
            if (mailboxId == 0)
                continue;

            final int unreadCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN);
            final int unseenCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNSEEN_COUNT_COLUMN);

            final Cursor folderCursor = contentResolver.query(EmailProvider.uiUri("uifolder", mailboxId),
                    UIProvider.FOLDERS_PROJECTION, null, null, null);

            if (folderCursor == null) {
                LogUtils.e(LOG_TAG, "Null folder cursor for account %d, mailbox %d", accountId, mailboxId);
                continue;
            }

            Folder folder = null;
            try {
                if (folderCursor.moveToFirst()) {
                    folder = new Folder(folderCursor);
                } else {
                    LogUtils.e(LOG_TAG, "Empty folder cursor for account %d, mailbox %d", accountId, mailboxId);
                    continue;
                }
            } finally {
                folderCursor.close();
            }

            LogUtils.d(LOG_TAG, "Changes to account " + account.name + ", folder: " + folder.name
                    + ", unreadCount: " + unreadCount + ", unseenCount: " + unseenCount);

            NotificationUtils.setNewEmailIndicator(context, unreadCount, unseenCount, account, folder, true);
        }
    } finally {
        mailboxCursor.close();
    }
}

From source file:com.android.email.NotificationController.java

private static void refreshNotificationsForAccountInternal(final Context context, final long accountId) {
    final ContentResolver contentResolver = context.getContentResolver();

    final Cursor accountCursor = contentResolver.query(EmailProvider.uiUri("uiaccount", accountId),
            UIProvider.ACCOUNTS_PROJECTION, null, null, null);

    if (accountCursor == null) {
        LogUtils.e(LOG_TAG, "Null account cursor for account id %d", accountId);
        return;/* w  w  w. j av  a 2  s  .  co m*/
    }

    com.android.mail.providers.Account account = null;
    try {
        if (accountCursor.moveToFirst()) {
            account = new com.android.mail.providers.Account(accountCursor);
        }
    } finally {
        accountCursor.close();
    }

    if (account == null) {
        LogUtils.d(LOG_TAG, "Tried to create a notification for a missing account %d", accountId);
        return;
    }

    final Cursor mailboxCursor = contentResolver.query(
            ContentUris.withAppendedId(EmailContent.MAILBOX_NOTIFICATION_URI, accountId), null, null, null,
            null);
    try {
        while (mailboxCursor.moveToNext()) {
            final long mailboxId = mailboxCursor.getLong(EmailContent.NOTIFICATION_MAILBOX_ID_COLUMN);
            if (mailboxId == 0)
                continue;

            final int unreadCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN);
            final int unseenCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNSEEN_COUNT_COLUMN);

            final Cursor folderCursor = contentResolver.query(EmailProvider.uiUri("uifolder", mailboxId),
                    UIProvider.FOLDERS_PROJECTION, null, null, null);

            if (folderCursor == null) {
                LogUtils.e(LOG_TAG, "Null folder cursor for account %d, mailbox %d", accountId, mailboxId);
                continue;
            }

            Folder folder = null;
            try {
                if (folderCursor.moveToFirst()) {
                    folder = new Folder(folderCursor);
                } else {
                    LogUtils.e(LOG_TAG, "Empty folder cursor for account %d, mailbox %d", accountId, mailboxId);
                    continue;
                }
            } finally {
                folderCursor.close();
            }

            LogUtils.d(LOG_TAG, "Changes to account " + account.name + ", folder: " + folder.name
                    + ", unreadCount: " + unreadCount + ", unseenCount: " + unseenCount);

            NotificationUtils.setNewEmailIndicator(context, unreadCount, unseenCount, account, folder, true);
        }
    } finally {
        mailboxCursor.close();
    }
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Rotate an image according to its EXIF data.
 *
 * @param context The Context/* w ww. j a va2s .co  m*/
 * @param uri     The Uri to the image file
 * @param bitmap  The Bitmap to rotate
 * @return The rotated Bitmap
 */
@NonNull
private static Bitmap rotatePhoto(@NonNull Context context, @NonNull Uri uri, @NonNull Bitmap bitmap) {
    uri = getImageUri(context, uri);
    int rotation = 0;

    if ("file".equals(uri.getScheme())) {
        try {
            final ExifInterface exif = new ExifInterface(uri.getPath());
            switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotation = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotation = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotation = 270;
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to read EXIF data for " + uri.toString(), e);
        }
    } else {
        final ContentResolver cr = context.getContentResolver();
        final String[] projection = new String[] { MediaStore.Images.ImageColumns.ORIENTATION };
        final Cursor cursor = cr.query(uri, projection, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst() && cursor.getColumnCount() > 0) {
                    rotation = cursor.getInt(0);
                }
            } finally {
                cursor.close();
            }
        }
    }

    if (rotation != 0) {
        final Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    return bitmap;
}

From source file:com.android.email.EmailNotificationController.java

private static void refreshNotificationsForAccountInternal(final Context context, final long accountId) {
    final Uri accountUri = EmailProvider.uiUri("uiaccount", accountId);

    final ContentResolver contentResolver = context.getContentResolver();

    final Cursor mailboxCursor = contentResolver.query(
            ContentUris.withAppendedId(EmailContent.MAILBOX_NOTIFICATION_URI, accountId), null, null, null,
            null);/*ww w  .j  ava2s  . c  om*/
    try {
        while (mailboxCursor.moveToNext()) {
            final long mailboxId = mailboxCursor.getLong(EmailContent.NOTIFICATION_MAILBOX_ID_COLUMN);
            if (mailboxId == 0)
                continue;

            final int unseenCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNSEEN_COUNT_COLUMN);

            final int unreadCount;
            // If nothing is unseen, clear the notification
            if (unseenCount == 0) {
                unreadCount = 0;
            } else {
                unreadCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN);
            }

            final Uri folderUri = EmailProvider.uiUri("uifolder", mailboxId);

            LogUtils.d(LOG_TAG, "Changes to account " + accountId + ", folder: " + mailboxId + ", unreadCount: "
                    + unreadCount + ", unseenCount: " + unseenCount);

            final Intent intent = new Intent(UIProvider.ACTION_UPDATE_NOTIFICATION);
            intent.setPackage(context.getPackageName());
            intent.setType(EmailProvider.EMAIL_APP_MIME_TYPE);

            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_ACCOUNT, accountUri);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_FOLDER, folderUri);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNREAD_COUNT, unreadCount);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNSEEN_COUNT, unseenCount);

            context.sendOrderedBroadcast(intent, null);
        }
    } finally {
        mailboxCursor.close();
    }
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Generate a thumbnail image file and save it to the persistent cache. If no photos exist for
 * the entry, te current file is deleted.
 *
 * @param context The Context//from  ww  w  . j  a va2s  . c om
 * @param id      Te ID for the entry
 */
private static void generateThumb(@NonNull Context context, long id) {
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        return;
    }

    final ContentResolver cr = context.getContentResolver();
    final Uri uri = Uri.withAppendedPath(Tables.Entries.CONTENT_ID_URI_BASE, id + "/photos");
    final String where = Tables.Photos.PATH + " NOT NULL";
    final Cursor cursor = cr.query(uri, new String[] { Tables.Photos.PATH }, where, null,
            Tables.Photos.POS + " ASC");
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                generateThumb(context, parsePath(cursor.getString(0)), id);
            } else {
                generateThumb(context, null, id);
            }
        } finally {
            cursor.close();
        }
    }
}

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

public static void updateContact(Context context, ContentResolver resolver, RawContact rawContact,
        boolean updateAvatar, boolean inSync, long rawContactId, BatchOperation batchOperation) {

    ContactsSync app = ContactsSync.getInstance();
    boolean existingAvatar = false;

    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION, DataQuery.SELECTION,
            new String[] { String.valueOf(rawContactId) }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, inSync,
            batchOperation);/*  w ww .ja va2  s  .co  m*/
    try {
        // Iterate over the existing rows of data, and update each one
        // with the information we received from the server.
        while (c.moveToNext()) {
            final long id = c.getLong(DataQuery.COLUMN_ID);
            final String mimeType = c.getString(DataQuery.COLUMN_MIMETYPE);
            final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
            if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {
                contactOp.updateName(uri, c.getString(DataQuery.COLUMN_GIVEN_NAME),
                        c.getString(DataQuery.COLUMN_FAMILY_NAME), rawContact.getFirstName(),
                        rawContact.getLastName());
                /*   } else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
                      final int type = c.getInt(DataQuery.COLUMN_PHONE_TYPE);
                      if (type == Phone.TYPE_MOBILE) {
                         existingCellPhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      } else if (type == Phone.TYPE_HOME) {
                         existingHomePhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      } else if (type == Phone.TYPE_WORK) {
                         existingWorkPhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      }
                   */
            } else if (mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
                existingAvatar = true;
                if (app.getSyncType() == ContactsSync.SyncType.LEGACY) {
                    contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), rawContact.getAvatarUrl(), uri);
                }
            }
        } // while
    } finally {
        c.close();
    }

    // Add the avatar if we didn't update the existing avatar
    if (app.getSyncType() != ContactsSync.SyncType.HARD && !existingAvatar) {
        contactOp.addAvatar(rawContact.getAvatarUrl());
    }

    // If we don't have a status profile, then create one. This could
    // happen for contacts that were created on the client - we don't
    // create the status profile until after the first sync...
    final String serverId = rawContact.getUid();
    final long profileId = lookupProfile(resolver, serverId);
    if (profileId <= 0) {
        contactOp.addProfileAction(serverId);
    }
}

From source file:com.marvin.rocklock.PlaylistUtils.java

/**
 * Writes to a playlist given a list of new song IDs and the playlist name
 *
 * @param context the activity calling this method
 * @param playlistName the playlist name
 * @param ids the song IDs to add/*from   www. j a v  a  2  s .c o m*/
 */
public static void writePlaylist(RockLockActivity context, String playlistName, ArrayList<String> ids) {

    ContentResolver resolver = context.getContentResolver();
    int playlistId = getPlaylistId(context, playlistName);

    Uri uri;
    int playOrder = 1;
    if (playlistId == -1) {
        // Case: new playlist
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Audio.Playlists.NAME, playlistName);
        // this might be missing a members extension...
        uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values);
    } else {
        // Case: exists playlist
        uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
        // Get most recent play order ID from playlist, so we can append
        Cursor orderCursor = resolver.query(uri, new String[] { MediaStore.Audio.Playlists.Members.PLAY_ORDER },
                null, null, MediaStore.Audio.Playlists.Members.PLAY_ORDER + " DESC ");

        if (orderCursor != null) {
            if (orderCursor.moveToFirst()) {
                playOrder = orderCursor.getInt(0) + 1;
            }
            orderCursor.close();
        }
    }

    Log.d("PLAYLIST ACTIVITY", String.format("Writing playlist %s", uri));

    // Add all the new tracks to the playlist.
    int size = ids.size();
    ContentValues values[] = new ContentValues[size];

    final ContentProviderClient provider = resolver.acquireContentProviderClient(uri);
    for (int i = 0; i < size; ++i) {
        values[i] = new ContentValues();
        values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, ids.get(i));
        values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, playOrder++);
        resolver.insert(uri, values[i]);
    }
    provider.release();
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Get the file name from a content Uri.
 *
 * @param cr  The ContentResolver//from  w  ww  . java 2  s .co m
 * @param uri The Uri
 * @return The file name
 */
@Nullable
private static String getName(@NonNull ContentResolver cr, @NonNull Uri uri) {
    if ("file".equals(uri.getScheme())) {
        return uri.getLastPathSegment();
    } else {
        final String[] projection = new String[] { MediaStore.MediaColumns.DISPLAY_NAME };
        final Cursor cursor = cr.query(uri, projection, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getString(0);
                }
            } finally {
                cursor.close();
            }
        }
    }
    return null;
}