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:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

private static List<Category> loadCategories(Context context) {
    Cursor data = TopekaDatabaseHelper.getCategoryCursor(context);
    List<Category> tmpCategories = new ArrayList<>(data.getCount());
    final SQLiteDatabase readableDatabase = TopekaDatabaseHelper.getReadableDatabase(context);
    do {//from w  w  w . j a  v  a  2 s.  c  o m
        final Category category = getCategory(data, readableDatabase);
        tmpCategories.add(category);
    } while (data.moveToNext());
    return tmpCategories;
}

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

public static List<RawContact> getStarredContacts(Context context, Uri uri) {
    Log.i(TAG, "*** Looking for starred contacts");

    final ContentResolver resolver = context.getContentResolver();

    Set<Long> contactIds = new HashSet<Long>();
    Cursor c = resolver.query(RawContacts.CONTENT_URI, new String[] { RawContacts.CONTACT_ID },
            RawContacts.STARRED + "!=0", null, null);
    try {//from w  w  w  .j  a va2 s.c o m
        while (c.moveToNext()) {
            contactIds.add(c.getLong(0));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    Log.i(TAG, "*** ... found " + contactIds.size() + " starred");

    int i = 0;
    StringBuilder sb = new StringBuilder();
    for (Long s : contactIds) {
        sb.append(s);
        if (++i >= Math.min(contactIds.size(), 50)) {
            break;
        }
        sb.append(",");
    }

    List<RawContact> contacts = new ArrayList<RawContact>();
    c = resolver.query(uri, new String[] { Contacts._ID, RawContacts.SOURCE_ID },
            RawContacts.CONTACT_ID + " IN (" + sb.toString() + ")", null, null);
    try {
        while (c.moveToNext()) {
            final long rawContactId = c.getLong(0);
            final String serverContactId = c.getString(1);
            RawContact rawContact = RawContact.create(rawContactId, serverContactId);
            contacts.add(rawContact);
        }
    } catch (Exception e) {
        Log.i(TAG, "failing .. " + e.toString());
    } finally {
        if (c != null) {
            c.close();
        }
    }

    Log.i(TAG, "*** ... and " + contacts.size() + " of mine " + sb.toString());
    return contacts;
}

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

private static ArrayList<Stop> doArrayListQuery(Context context, String query) {
    ArrayList<Stop> stops = new ArrayList<Stop>();

    Log.d(TAG, "query: " + query);

    DatabaseHelper databaseHelper = new DatabaseHelper(context);
    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    Cursor cursor = database.rawQuery(query, null);

    try {/*from w w w.  j a va 2s.  c o  m*/
        if (cursor.moveToFirst()) {
            do {
                Stop stop = new Stop();
                stop.platformTag = cursor.getString(0);
                stop.platformNumber = cursor.getString(1);
                stop.name = cursor.getString(2);
                stop.roadName = cursor.getString(3);
                stop.latitude = cursor.getDouble(4);
                stop.longitude = cursor.getDouble(5);
                stops.add(stop);
            } while (cursor.moveToNext());
        }
    } finally {
        cursor.close();
    }
    Log.d(TAG, "stops.size() = " + stops.size());
    database.close();
    return stops;
}

From source file:Main.java

public static String queryAudioName(Context context, Uri name) {
    String audioId;// w ww  . java 2  s  .com
    String uriName = name.toString();
    uriName = uriName.substring(uriName.lastIndexOf("/") + 1);
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
            null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        int counter = cursor.getCount();
        for (int j = 0; j < counter; j++) {
            audioId = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));

            if (uriName.equals(audioId)) {
                uriName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            } else {
                Ringtone ringtone = RingtoneManager.getRingtone(context, name);
                uriName = ringtone.getTitle(context);
                break;
            }
            cursor.moveToNext();

        }
        cursor.close();
    } else {
        try {
            Ringtone ringtone = RingtoneManager.getRingtone(context, name);
            uriName = ringtone.getTitle(context);
        } catch (Exception e) {
            return uriName;
        }
    }
    return uriName;
}

From source file:at.bitfire.davdroid.mirakel.resource.LocalCalendar.java

public static LocalCalendar[] findAll(Account account, ContentProviderClient providerClient, Context ctx)
        throws RemoteException {
    @Cleanup
    Cursor cursor = providerClient.query(calendarsURI(account), new String[] { Calendars._ID, Calendars.NAME },
            Calendars.DELETED + "=0 AND " + Calendars.SYNC_EVENTS + "=1", null, null);

    LinkedList<LocalCalendar> calendars = new LinkedList<LocalCalendar>();
    while (cursor != null && cursor.moveToNext())
        calendars.add(new LocalCalendar(account, providerClient, cursor.getInt(0), cursor.getString(1), ctx));
    return calendars.toArray(new LocalCalendar[0]);
}

From source file:free.yhc.netmbuddy.share.Json.java

static JSONObject playlistToJson(long plid) {
    final int COLI_ID = 0;
    Cursor c = DB.get().queryVideos(plid, new ColVideo[] { ColVideo.ID }, null, false);
    if (!c.moveToFirst()) {
        c.close();//from  w  w  w  .ja  v  a  2  s  . c o  m
        return null;
    }

    JSONObject jo = new JSONObject();
    try {
        jo.put(FTITLE, DB.get().getPlaylistInfo(plid, ColPlaylist.TITLE));
        String thumbnailYtvid = (String) DB.get().getPlaylistInfo(plid, ColPlaylist.THUMBNAIL_YTVID);
        if (Utils.isValidValue(thumbnailYtvid))
            jo.put(FTHUMBNAIL_YTVID, thumbnailYtvid);

        JSONArray jarr = new JSONArray();
        do {
            JSONObject jov = videoToJson(c.getLong(COLI_ID));
            eAssert(null != jov);
            jarr.put(jov);
        } while (c.moveToNext());
        jo.put(FVIDEOS, jarr);
    } catch (JSONException e) {
        jo = null;
    }
    c.close();

    return jo;
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static void cleanupTreeByResourcePath(String resourcePath) {
    Log.i(TAG, "cleaning up tree of: " + resourcePath);
    String kindString = MetaUtilities.getStringField(resourcePath, Nodes.NODE_KIND);
    if (kindString == null) {
        return;/* w w  w  . j  a va2s.  co  m*/
    }

    U1NodeKind kind = U1NodeKind.valueOf(kindString.toUpperCase(Locale.US));
    if (kind == U1NodeKind.FILE) {
        String data = FileUtilities.getFilePathFromResourcePath(resourcePath);
        FileUtilities.removeSilently(data);
        MetaUtilities.deleteByResourcePath(resourcePath);
    } else {
        String resourcePathFmt = resourcePath + "/%";
        String[] projection = new String[] { Nodes.NODE_RESOURCE_PATH, Nodes.NODE_DATA };
        String selection = Nodes.NODE_RESOURCE_PATH + " LIKE ?";
        String[] selectionArgs = new String[] { resourcePathFmt };

        Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
        if (c != null) {
            try {
                while (c.moveToNext()) {
                    String data = FileUtilities.getFilePathFromResourcePath(resourcePathFmt);
                    FileUtilities.removeSilently(data);
                }
            } finally {
                c.close();
            }
        }

        sResolver.delete(Nodes.CONTENT_URI, selection, selectionArgs);

        selection = Nodes.NODE_RESOURCE_PATH + "=?";
        selectionArgs = new String[] { resourcePath };
        sResolver.delete(Nodes.CONTENT_URI, selection, selectionArgs);
    }
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

static List<TaskList> loadNewListsFromDB(final Context context, final GoogleTaskList remoteList) {
    final Cursor c = context.getContentResolver().query(TaskList.URI, TaskList.Columns.FIELDS,
            GoogleTaskList.getTaskListWithoutRemoteClause(), remoteList.getTaskListWithoutRemoteArgs(), null);
    final ArrayList<TaskList> lists = new ArrayList<TaskList>();
    try {/*  w  w w  .j  av  a 2 s.co  m*/
        while (c.moveToNext()) {
            lists.add(new TaskList(c));
        }
    } finally {
        if (c != null)
            c.close();
    }

    return lists;
}

From source file:com.tct.email.LegacyConversions.java

/**
 * Read a complete Provider message into a legacy message (for IMAP upload).  This
 * is basically the equivalent of LocalFolder.getMessages() + LocalFolder.fetch().
 *//*  w w w .java  2  s . c  o  m*/
public static Message makeMessage(final Context context, final EmailContent.Message localMessage)
        throws MessagingException {
    final MimeMessage message = new MimeMessage();

    // LocalFolder.getMessages() equivalent:  Copy message fields
    message.setSubject(localMessage.mSubject == null ? "" : localMessage.mSubject);
    final Address[] from = Address.fromHeader(localMessage.mFrom);
    if (from.length > 0) {
        message.setFrom(from[0]);
    }
    message.setSentDate(new Date(localMessage.mTimeStamp));
    message.setUid(localMessage.mServerId);
    message.setFlag(Flag.DELETED, localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_DELETED);
    message.setFlag(Flag.SEEN, localMessage.mFlagRead);
    message.setFlag(Flag.FLAGGED, localMessage.mFlagFavorite);
    //      message.setFlag(Flag.DRAFT, localMessage.mMailboxKey == draftMailboxKey);
    message.setRecipients(RecipientType.TO, Address.fromHeader(localMessage.mTo));
    message.setRecipients(RecipientType.CC, Address.fromHeader(localMessage.mCc));
    message.setRecipients(RecipientType.BCC, Address.fromHeader(localMessage.mBcc));
    message.setReplyTo(Address.fromHeader(localMessage.mReplyTo));
    message.setInternalDate(new Date(localMessage.mServerTimeStamp));
    message.setMessageId(localMessage.mMessageId);
    message.setPriority(localMessage.mPriority);//[FEATURE]-Add-BEGIN by TCTNj.fu.zhang,04/03/2014,622697
    // LocalFolder.fetch() equivalent: build body parts
    message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
    final MimeMultipart mp = new MimeMultipart();
    mp.setSubType("mixed");
    message.setBody(mp);

    try {
        addTextBodyPart(mp, "text/html",
                EmailContent.Body.restoreBodyHtmlWithMessageId(context, localMessage.mId));
    } catch (RuntimeException rte) {
        LogUtils.d(Logging.LOG_TAG, "Exception while reading html body " + rte.toString());
    }

    try {
        addTextBodyPart(mp, "text/plain",
                EmailContent.Body.restoreBodyTextWithMessageId(context, localMessage.mId));
    } catch (RuntimeException rte) {
        LogUtils.d(Logging.LOG_TAG, "Exception while reading text body " + rte.toString());
    }

    // Attachments
    final Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    final Cursor attachments = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null,
            null, null);

    try {
        while (attachments != null && attachments.moveToNext()) {
            final Attachment att = new Attachment();
            att.restore(attachments);
            try {
                final InputStream content;
                if (att.mContentBytes != null) {
                    // This is generally only the case for synthetic attachments, such as those
                    // generated by unit tests or calendar invites
                    content = new ByteArrayInputStream(att.mContentBytes);
                } else {
                    String contentUriString = att.getCachedFileUri();
                    if (TextUtils.isEmpty(contentUriString)) {
                        contentUriString = att.getContentUri();
                    }
                    if (TextUtils.isEmpty(contentUriString)) {
                        content = null;
                    } else {
                        final Uri contentUri = Uri.parse(contentUriString);
                        content = context.getContentResolver().openInputStream(contentUri);
                    }
                }
                final String mimeType = att.mMimeType;
                final Long contentSize = att.mSize;
                final String contentId = att.mContentId;
                final String filename = att.mFileName;
                if (content != null) {
                    addAttachmentPart(mp, mimeType, contentSize, filename, contentId, content);
                } else {
                    LogUtils.e(LogUtils.TAG, "Could not open attachment file for upsync");
                }
            } catch (final FileNotFoundException e) {
                LogUtils.e(LogUtils.TAG, "File Not Found error on %s while upsyncing message",
                        att.getCachedFileUri());
            }
        }
    } finally {
        if (attachments != null) {
            attachments.close();
        }
    }

    return message;
}

From source file:com.tct.email.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message.// w  w  w.ja v  a 2s .  c  o  m
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context      a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part         a single attachment part from POP or IMAP
 * @param index        add for pop re-download attachment
 * @param protocol   add to judge if it's pop3,it can be used later
 * @param isInline     add to judge if it's isInline attachment
 */
public static void addOneAttachment(final Context context, final EmailContent.Message localMessage,
        final Part part, int index, String protocol, boolean isInline) throws MessagingException, IOException {
    Attachment localAttachment = mimePartToAttachment(context, part, index, protocol, isInline);
    // TS: Gantao 2015-06-04 EMAIL BUGFIX_1009030 MOD_E
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mAccountKey = localMessage.mAccountKey;

    if (DEBUG_ATTACHMENTS) {
        LogUtils.d(Logging.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    final Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    final Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null,
            null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            final Attachment dbAttachment = new Attachment();
            dbAttachment.restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (!TextUtils.equals(dbAttachment.mFileName, localAttachment.mFileName)
                    || !TextUtils.equals(dbAttachment.mMimeType, localAttachment.mMimeType)
                    || !TextUtils.equals(dbAttachment.mContentId, localAttachment.mContentId)
                    || !TextUtils.equals(dbAttachment.mLocation, localAttachment.mLocation)) {
                continue;
            }
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                LogUtils.d(Logging.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    //TS: Gantao 2015-07-16 EMAIL BUGFIX_1045624 MOD_S
    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }
    // If an attachment body was actually provided, we need to write the file now
    saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);
    //TS: Gantao 2015-07-16 EMAIL BUGFIX_1045624 MOD_E
    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_852100 MOD_S
    Body body = Body.restoreBodyWithMessageId(context, localAttachment.mMessageKey);
    ContentValues cv = new ContentValues();
    if (body != null && body.mHtmlContent != null && localAttachment.mContentId != null
            && localAttachment.getContentUri() != null) {
        cv.clear();
        String html = body.mHtmlContent;
        String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + localAttachment.mContentId + "\\E\"";
        //TS: zhaotianyong 2015-03-23 EMAIL BUGFIX_899799 MOD_S
        //TS: zhaotianyong 2015-04-01 EMAIL BUGFIX_962560 MOD_S
        String srcContentUri = " src=\"" + localAttachment.getContentUri() + "\"";
        //TS: zhaotianyong 2015-04-01 EMAIL BUGFIX_962560 MOD_E
        //TS: zhaotianyong 2015-03-23 EMAIL BUGFIX_899799 MOD_E
        //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
        try {
            html = html.replaceAll(contentIdRe, srcContentUri);
        } catch (PatternSyntaxException e) {
            LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
        }
        //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
        cv.put(BodyColumns.HTML_CONTENT, html);
        Body.updateBodyWithMessageId(context, localAttachment.mMessageKey, cv);
        Body.restoreBodyHtmlWithMessageId(context, localAttachment.mMessageKey);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_852100 MOD_E
    localMessage.mAttachments.add(localAttachment);
    //TS: Gantao 2015-09-28 EMAIL FEATURE_526529 MOD_S
    //We do not think the inline images is an attachment from now.
    if (!isInline) {
        localMessage.mFlagAttachment = true;
    }
    //TS: Gantao 2015-09-28 EMAIL FEATURE_526529 MOD_E
}