Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:Main.java

static public void dumpCursor(Cursor cursor) {
    final String LOG_TAG = "dumpCursor";
    if (cursor != null) {
        Log.d(LOG_TAG, "cursor " + cursor.getCount());
        for (int i = 0; i < cursor.getColumnCount(); i++)
            Log.d(LOG_TAG, "col " + i + " " + cursor.getColumnName(i));

        cursor.moveToFirst();/* w  w w.ja va 2  s .co  m*/
        String[] a = new String[cursor.getColumnCount()];
        while (!cursor.isAfterLast()) {
            for (int i = 0; i < a.length; i++)
                a[i] = cursor.getString(i);
            Log.d(LOG_TAG, Arrays.toString(a));
            cursor.moveToNext();
        }

        cursor.moveToFirst();
    }
}

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * In support of deleting a mailbox, find all messages and delete their attachments.
 *
 * @param context//from w w  w.  j a va 2  s . c o  m
 * @param accountId the account for the mailbox
 * @param mailboxId the mailbox for the messages
 */
public static void deleteAllMailboxAttachmentFiles(Context context, long accountId, long mailboxId) {
    Cursor c = context.getContentResolver().query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
            MessageColumns.MAILBOX_KEY + "=?", new String[] { Long.toString(mailboxId) }, null);
    try {
        while (c.moveToNext()) {
            long messageId = c.getLong(Message.ID_PROJECTION_COLUMN);
            deleteAllAttachmentFiles(context, accountId, messageId);
        }
    } finally {
        c.close();
    }
}

From source file:org.c99.SyncProviderDemo.ContactsSyncAdapterService.java

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        String status) {//from   w  w w  .  j a  v a2  s.c o m
    Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
    Cursor c = mContentResolver.query(entityUri,
            new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null,
            null);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);

                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.profile")) {
                    ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newInsert(ContactsContract.StatusUpdates.CONTENT_URI);
                    builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1));
                    builder.withValue(ContactsContract.StatusUpdates.STATUS, status);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE,
                            "org.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.logo);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP,
                            System.currentTimeMillis());
                    operationList.add(builder.build());

                    //Only change the text of our custom entry to the status message pre-Honeycomb, as the newer contacts app shows
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static List<MhSpRequest> listLatestRequestsSince(Context context, String trollId, int dayCount) {
    List<MhSpRequest> result = new ArrayList<MhSpRequest>();

    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.HOUR_OF_DAY, dayCount * -24);
    Date sinceDate = instance.getTime();

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Calendar calendar = Calendar.getInstance();

    Cursor cursor = database.rawQuery(SQL_LIST_REQUESTS_SINCE,
            new String[] { trollId, "" + sinceDate.getTime() });
    while (cursor.moveToNext()) {
        long startTimeMillis = cursor.getLong(0);
        long endTimeMillis = cursor.getLong(1);
        String scriptName = cursor.getString(2);
        String status = cursor.getString(3);

        calendar.setTimeInMillis(startTimeMillis);
        Date date = calendar.getTime();
        PublicScript script = PublicScript.valueOf(scriptName);

        long duration = 0;
        if (endTimeMillis > 0) {
            duration = endTimeMillis - startTimeMillis;
        }//from  w  w w .  ja  va  2s .co m
        MhSpRequest request = new MhSpRequest(date, duration, script, status);
        result.add(request);
    }

    cursor.close();
    database.close();

    return result;
}

From source file:cc.softwarefactory.lokki.android.utilities.Utils.java

public static Bitmap getPhotoFromEmail(Context context, String email) {

    if (context == null || email == null) {
        return null;
    }/* ww w  .  j a  v  a2s  .c om*/

    Bitmap result = MainApplication.avatarCache.get(email);
    if (result != null) {
        Log.e(TAG, "getPhotoFromEmail IN cache, Email: " + email);
        return result;
    }

    if (loadContacts(context)) {
        try {
            Log.e(TAG, "getPhotoFromEmail - Email: " + email + ", id: "
                    + MainApplication.contacts.getJSONObject(email).getLong("id"));
            result = openPhoto(context, MainApplication.contacts.getJSONObject(email).getLong("id"));
        } catch (JSONException e) {
            Log.e(TAG, "getPhotoFromEmail - failed: " + email);
        }
    } else {
        Log.e(TAG, "getPhotoFromEmail - id queried: " + email);
        Cursor emailCursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.DATA + "='" + email + "'", null, null);
        while (emailCursor != null && emailCursor.moveToNext()) {
            Long contactId = Long.valueOf(emailCursor
                    .getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID)));
            result = openPhoto(context, contactId);
        }
        if (emailCursor != null) {
            emailCursor.close();
        }
    }

    if (result == null) {
        String name = getNameFromEmail(context, email);
        result = Utils.getDefaultAvatarInitials(context, name);
    }

    MainApplication.avatarCache.put(email, result);
    return result;
}

From source file:cc.softwarefactory.lokki.android.utilities.Utils.java

public static String getNameFromEmail(Context context, String email) {

    if (context == null) {
        return null;
    }/*from   w  w w. j  a va2s .  com*/

    if (loadContacts(context)) {
        try {
            String name = MainApplication.contacts.getJSONObject(email).getString("name");
            Log.e(TAG, "getNameFromEmail - Email: " + email + ", Name: " + name);
            return name;
        } catch (JSONException e) {
            Log.e(TAG, "getNameFromEmail - failed: " + email);
        }
    }

    Log.e(TAG, "getNameFromEmail - Name queried: " + email);
    Cursor emailCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
            null, ContactsContract.CommonDataKinds.Email.DATA + "='" + email + "'", null, null);
    if (emailCursor == null) {
        return "???";
    }
    if (emailCursor.moveToNext()) {
        String name = emailCursor.getString(
                emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY));
        Log.e(TAG, "getNameFromEmail - Email: " + email + ", Name: " + name);
        emailCursor.close();
        return name;
    }
    emailCursor.close();
    return email;
}

From source file:edu.mit.mobile.android.locast.data.TaggableItem.java

/**
 * TODO make this pick the set of tags for a set of content.
 *
 * @param cr a content resolver/*from  ww w  .j a  v  a2  s  .c  o m*/
 * @return the top MAX_POPULAR_TAGS most popular tags in the set, with the most popular first.
 */
public static List<String> getPopularTags(ContentResolver cr) {

    final Map<String, Integer> tagPop = new HashMap<String, Integer>();
    final List<String> popTags;

    final Cursor c = cr.query(Tag.CONTENT_URI, Tag.DEFAULT_PROJECTION, null, null, null);
    final int tagColumn = c.getColumnIndex(Tag._NAME);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        final String tag = c.getString(tagColumn);

        final Integer count = tagPop.get(tag);
        if (count == null) {
            tagPop.put(tag, 1);
        } else {
            tagPop.put(tag, count + 1);
        }
    }
    c.close();

    popTags = new ArrayList<String>(tagPop.keySet());

    Collections.sort(popTags, new Comparator<String>() {
        public int compare(String object1, String object2) {
            return tagPop.get(object2).compareTo(tagPop.get(object1));
        }

    });
    int limit;
    if (popTags.size() < MAX_POPULAR_TAGS) {
        limit = popTags.size();
    } else {
        limit = MAX_POPULAR_TAGS;
    }
    return popTags.subList(0, limit);
}

From source file:Main.java

public static long[] getSongListForCursor(Cursor cursor) {
    if (cursor == null) {
        return sEmptyList;
    }//from   w w  w . j a v a 2s. com
    int len = cursor.getCount();
    long[] list = new long[len];
    cursor.moveToFirst();
    int colidx = -1;
    try {
        colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
    } catch (IllegalArgumentException ex) {
        colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
    }
    for (int i = 0; i < len; i++) {
        list[i] = cursor.getLong(colidx);
        cursor.moveToNext();
    }
    return list;
}

From source file:at.bitfire.davdroid.resource.LocalGroup.java

/**
 * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships
 * are (if possible) applied, keeping cached memberships in sync.
 * @param addressBook    address book to take groups from
 * @throws ContactsStorageException on contact provider errors
 *///  w  w w.ja v a  2  s.c o m
public static void applyPendingMemberships(LocalAddressBook addressBook) throws ContactsStorageException {
    try {
        @Cleanup
        Cursor cursor = addressBook.provider.query(addressBook.syncAdapterURI(Groups.CONTENT_URI),
                new String[] { Groups._ID, COLUMN_PENDING_MEMBERS }, COLUMN_PENDING_MEMBERS + " IS NOT NULL",
                new String[] {}, null);

        BatchOperation batch = new BatchOperation(addressBook.provider);
        while (cursor != null && cursor.moveToNext()) {
            long id = cursor.getLong(0);
            Constants.log.fine("Assigning members to group " + id);

            // delete all memberships and cached memberships for this group
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                    .withSelection(
                            "(" + GroupMembership.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                                    + "=?) OR (" + CachedGroupMembership.MIMETYPE + "=? AND "
                                    + CachedGroupMembership.GROUP_ID + "=?)",
                            new String[] { GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id),
                                    CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) })
                    .withYieldAllowed(true)));

            // extract list of member UIDs
            List<String> members = new LinkedList<>();
            byte[] raw = cursor.getBlob(1);
            @Cleanup("recycle")
            Parcel parcel = Parcel.obtain();
            parcel.unmarshall(raw, 0, raw.length);
            parcel.setDataPosition(0);
            parcel.readStringList(members);

            // insert memberships
            for (String uid : members) {
                Constants.log.fine("Assigning member: " + uid);
                try {
                    LocalContact member = addressBook.findContactByUID(uid);
                    member.addToGroup(batch, id);
                } catch (FileNotFoundException e) {
                    Constants.log.log(Level.WARNING, "Group member not found: " + uid, e);
                }
            }

            // remove pending memberships
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)))
                    .withValue(COLUMN_PENDING_MEMBERS, null).withYieldAllowed(true)));

            batch.commit();
        }
    } catch (RemoteException e) {
        throw new ContactsStorageException("Couldn't get pending memberships", e);
    }
}

From source file:im.delight.android.commons.Social.java

/**
 * Returns a list of phone numbers for the contact with the given lookup ID
 *
 * @param contactLookupId a contact's lookup ID to get the phone numbers for
 * @param context a context reference//from   ww w  .  ja v a  2  s .c  om
 * @return CharSequence[] a list of all phone numbers for the given contact or `null`
 */
public static CharSequence[] getContactPhone(final String contactLookupId, final Context context) {
    final Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    final String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
    final String where = ContactsContract.Contacts.LOOKUP_KEY + " = ?";
    final String[] selectionArgs = new String[] { contactLookupId };
    final String sortOrder = null;

    Cursor result = context.getContentResolver().query(uri, projection, where, selectionArgs, sortOrder);

    String phone;
    if (result != null) {
        if (result.getCount() > 0) {
            final CharSequence[] res = new CharSequence[result.getCount()];

            int i = 0;
            while (result.moveToNext()) {
                phone = result.getString(result.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                if (phone != null) {
                    res[i] = phone;
                    i++;
                }
            }

            result.close();

            return res;
        } else {
            result.close();

            return null;
        }
    } else {
        return null;
    }
}