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.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

/**
 * Loads the remote lists from the database and merges the two lists. If the
 * remote list contains all lists, then this method only adds local db-ids
 * to the items. If it does not contain all of them, this loads whatever
 * extra items are known in the db to the list also.
 * /*  w  w  w  .j  a  va  2  s.  c om*/
 * Since all lists are expected to be downloaded, any non-existing entries
 * are assumed to be deleted and marked as such.
 */
public static void mergeListsWithLocalDB(final Context context, final String account,
        final List<GoogleTaskList> remoteLists) {
    Log.d(TAG, "mergeList starting with: " + remoteLists.size());

    final HashMap<String, GoogleTaskList> localVersions = new HashMap<String, GoogleTaskList>();
    final Cursor c = context.getContentResolver().query(GoogleTaskList.URI, GoogleTaskList.Columns.FIELDS,
            GoogleTaskList.Columns.ACCOUNT + " IS ? AND " + GoogleTaskList.Columns.SERVICE + " IS ?",
            new String[] { account, GoogleTaskList.SERVICENAME }, null);
    try {
        while (c.moveToNext()) {
            GoogleTaskList list = new GoogleTaskList(c);
            localVersions.put(list.remoteId, list);
        }
    } finally {
        if (c != null)
            c.close();
    }

    for (final GoogleTaskList remotelist : remoteLists) {
        // Merge with hashmap
        if (localVersions.containsKey(remotelist.remoteId)) {
            //Log.d(TAG, "Setting merge id");
            remotelist.dbid = localVersions.get(remotelist.remoteId).dbid;
            //Log.d(TAG, "Setting merge delete status");
            remotelist.setDeleted(localVersions.get(remotelist.remoteId).isDeleted());
            localVersions.remove(remotelist.remoteId);
        }
    }

    // Remaining ones
    for (final GoogleTaskList list : localVersions.values()) {
        list.remotelyDeleted = true;
        remoteLists.add(list);
    }
    Log.d(TAG, "mergeList finishing with: " + remoteLists.size());
}

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

static List<Task> loadNewTasksFromDB(final Context context, final long listdbid, final String account) {
    final Cursor c = context.getContentResolver().query(Task.URI, Task.Columns.FIELDS,
            GoogleTask.getTaskWithoutRemoteClause(),
            GoogleTask.getTaskWithoutRemoteArgs(listdbid, account, GoogleTaskList.SERVICENAME), null);
    final ArrayList<Task> tasks = new ArrayList<Task>();
    try {//from w w  w .  j  a  v  a 2s .  co m
        while (c.moveToNext()) {
            tasks.add(new Task(c));
        }
    } finally {
        if (c != null)
            c.close();
    }

    return tasks;
}

From source file:busradar.madison.StopDialog.java

static RouteURL[] get_time_urls(int stopid) {
    Cursor c = G.db.rawQuery("SELECT url, route " + "FROM routestops " + "WHERE stopid = ? " + "ORDER BY route",
            new String[] { stopid + "" });

    RouteURL[] list = new RouteURL[c.getCount()];
    //ArrayList<RouteURL> list = new ArrayLst<RouteURL>();
    //int last = -1;
    int i = 0;/*w  ww.  j av a2 s .  c o  m*/
    while (c.moveToNext()) {
        RouteURL r = new RouteURL();
        r.url = c.getString(0);
        r.route = c.getInt(1);
        list[i++] = r;

    }

    c.close();
    return list;
}

From source file:com.android.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 ww  .  j a va2 s.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 upgrading true if upgrading a local account - handle attachments differently
 * @throws IOException
 */
private static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part,
        boolean upgrading) throws MessagingException, IOException {

    Attachment localAttachment = new Attachment();

    // Transfer fields from mime format to provider format
    String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
    String name = MimeUtility.getHeaderParameter(contentType, "name");
    if (name == null) {
        String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
        name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
    }

    // Select the URI for the new attachments.  For attachments downloaded by the legacy
    // IMAP/POP code, this is not determined yet, so is null (it will be rewritten below,
    // or later, when the actual attachment file is created.)
    //
    // When upgrading older local accounts, the URI represents a local asset (e.g. a photo)
    // so we need to preserve the URI.
    // TODO This works for outgoing messages, where the URI does not change.  May need
    // additional logic to handle the case of rewriting URI for received attachments.
    Uri contentUri = null;
    String contentUriString = null;
    if (upgrading) {
        Body body = part.getBody();
        if (body instanceof LocalStore.LocalAttachmentBody) {
            LocalStore.LocalAttachmentBody localBody = (LocalStore.LocalAttachmentBody) body;
            contentUri = localBody.getContentUri();
            if (contentUri != null) {
                contentUriString = contentUri.toString();
            }
        }
    }

    // Find size, if available, via a number of techniques:
    long size = 0;
    if (upgrading) {
        // If upgrading a legacy account, the size must be recaptured from the data source
        if (contentUri != null) {
            Cursor metadataCursor = context.getContentResolver().query(contentUri,
                    ATTACHMENT_META_COLUMNS_PROJECTION, null, null, null);
            if (metadataCursor != null) {
                try {
                    if (metadataCursor.moveToFirst()) {
                        size = metadataCursor.getInt(ATTACHMENT_META_COLUMNS_SIZE);
                    }
                } finally {
                    metadataCursor.close();
                }
            }
        }
        // TODO: a downloaded legacy attachment - see if the above code works
    } else {
        // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
        String disposition = part.getDisposition();
        if (disposition != null) {
            String s = MimeUtility.getHeaderParameter(disposition, "size");
            if (s != null) {
                size = Long.parseLong(s);
            }
        }
    }

    // Get partId for unloaded IMAP attachments (if any)
    // This is only provided (and used) when we have structure but not the actual attachment
    String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
    String partId = partIds != null ? partIds[0] : null;

    localAttachment.mFileName = name;
    localAttachment.mMimeType = part.getMimeType();
    localAttachment.mSize = size; // May be reset below if file handled
    localAttachment.mContentId = part.getContentId();
    localAttachment.mContentUri = contentUriString;
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings

    if (DEBUG_ATTACHMENTS) {
        Log.d(Email.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.
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            Attachment dbAttachment = new Attachment().restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName))
                continue;
            if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType))
                continue;
            if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId))
                continue;
            if (stringNotEqual(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) {
                Log.d(Email.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    // 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
    if (!upgrading) {
        saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);
    }

    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    localMessage.mAttachments.add(localAttachment);
    localMessage.mFlagAttachment = true;
}

From source file:org.fdroid.enigtext.mms.MmsCommunication.java

protected static MmsConnectionParameters getMmsConnectionParameters(Context context, String apn,
        boolean proxyIfPossible) throws ApnUnavailableException {
    Cursor cursor = null;

    try {//from   ww  w  .  j av a 2  s .  c o m
        cursor = DatabaseFactory.getMmsDatabase(context).getCarrierMmsInformation(apn);

        if (cursor == null || !cursor.moveToFirst())
            return getLocalMmsConnectionParameters(context);

        do {
            String mmsc = cursor.getString(cursor.getColumnIndexOrThrow("mmsc"));
            String proxy = null;
            String port = null;

            if (proxyIfPossible) {
                proxy = cursor.getString(cursor.getColumnIndexOrThrow("mmsproxy"));
                port = cursor.getString(cursor.getColumnIndexOrThrow("mmsport"));
            }

            if (!Util.isEmpty(mmsc))
                return new MmsConnectionParameters(mmsc, proxy, port);

        } while (cursor.moveToNext());

        return getLocalMmsConnectionParameters(context);
    } catch (SQLiteException sqe) {
        Log.w("MmsCommunication", sqe);
        return getLocalMmsConnectionParameters(context);
    } catch (SecurityException se) {
        Log.w("MmsCommunication", se);
        return getLocalMmsConnectionParameters(context);
    } catch (IllegalArgumentException iae) {
        Log.w("MmsCommunication", iae);
        return getLocalMmsConnectionParameters(context);
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

public static int findReplace(Collection col, List<Long> nids, String src, String dst, boolean isRegex,
        String field, boolean fold) {
    Map<Long, Integer> mmap = new HashMap<Long, Integer>();
    if (field != null) {
        try {/*ww  w .ja  v a  2s. c o  m*/
            for (JSONObject m : col.getModels().all()) {
                JSONArray flds = m.getJSONArray("flds");
                for (int fi = 0; fi < flds.length(); ++fi) {
                    JSONObject f = flds.getJSONObject(fi);
                    if (f.getString("name").equals(field)) {
                        mmap.put(m.getLong("id"), f.getInt("ord"));
                    }
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        if (mmap.isEmpty()) {
            return 0;
        }
    }
    // find and gather replacements
    if (!isRegex) {
        src = Pattern.quote(src);
    }
    if (fold) {
        src = "(?i)" + src;
    }
    Pattern regex = Pattern.compile(src);

    ArrayList<Object[]> d = new ArrayList<Object[]>();
    String sql = "select id, mid, flds from notes where id in " + Utils.ids2str(nids.toArray(new Long[] {}));
    nids = new ArrayList<Long>();

    Cursor cur = null;
    try {
        cur = col.getDb().getDatabase().rawQuery(sql, null);
        while (cur.moveToNext()) {
            String flds = cur.getString(2);
            String origFlds = flds;
            // does it match?
            String[] sflds = Utils.splitFields(flds);
            if (field != null) {
                long mid = cur.getLong(1);
                if (!mmap.containsKey(mid)) {
                    continue;
                }
                int ord = mmap.get(mid);
                sflds[ord] = regex.matcher(sflds[ord]).replaceAll(dst);
            } else {
                for (int i = 0; i < sflds.length; ++i) {
                    sflds[i] = regex.matcher(sflds[i]).replaceAll(dst);
                }
            }
            flds = Utils.joinFields(sflds);
            if (!flds.equals(origFlds)) {
                long nid = cur.getLong(0);
                nids.add(nid);
                d.add(new Object[] { flds, Utils.intNow(), col.usn(), nid });
            }

        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (d.isEmpty()) {
        return 0;
    }
    // replace
    col.getDb().executeMany("update notes set flds=?,mod=?,usn=? where id=?", d);
    long[] pnids = Utils.toPrimitive(nids);
    col.updateFieldCache(pnids);
    col.genCards(pnids);
    return d.size();
}

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

public static Set<Integer> getRootNodeIds() {
    Set<Integer> ids = new TreeSet<Integer>();
    final String[] projection = new String[] { Nodes._ID };
    final String selection = Nodes.NODE_PARENT_PATH + " IS NULL";
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, null, null);
    try {//from  w ww . j  a  v a2s.c o m
        if (c.moveToFirst()) {
            int id;
            do {
                id = c.getInt(c.getColumnIndex(Nodes._ID));
                ids.add(id);
            } while (c.moveToNext());
        }
    } finally {
        c.close();
    }
    return ids;
}

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

/**
 * Loads the remote tasks from the database and merges the two lists. If the
 * remote list contains all items, then this method only adds local db-ids
 * to the items. If it does not contain all of them, this loads whatever
 * extra items are known in the db to the list also.
 *///w w  w.j  a  v  a  2  s.  c  o  m
public static void mergeTasksWithLocalDB(final Context context, final String account,
        final List<GoogleTask> remoteTasks, long listDbId) {
    final HashMap<String, GoogleTask> localVersions = new HashMap<String, GoogleTask>();
    final Cursor c = context.getContentResolver().query(GoogleTask.URI, GoogleTask.Columns.FIELDS,
            GoogleTask.Columns.LISTDBID + " IS ? AND " + GoogleTask.Columns.ACCOUNT + " IS ? AND "
                    + GoogleTask.Columns.SERVICE + " IS ?",
            new String[] { Long.toString(listDbId), account, GoogleTaskList.SERVICENAME }, null);
    try {
        while (c.moveToNext()) {
            GoogleTask task = new GoogleTask(c);
            localVersions.put(task.remoteId, task);
        }
    } finally {
        if (c != null)
            c.close();
    }

    for (final GoogleTask task : remoteTasks) {
        // Set list on remote objects
        task.listdbid = listDbId;
        // Merge with hashmap
        if (localVersions.containsKey(task.remoteId)) {
            task.dbid = localVersions.get(task.remoteId).dbid;
            task.setDeleted(localVersions.get(task.remoteId).isDeleted());
            if (task.isDeleted()) {
                Log.d(TAG, "merge1: deleting " + task.title);
            }
            localVersions.remove(task.remoteId);
        }
    }

    // Remaining ones
    for (final GoogleTask task : localVersions.values()) {
        remoteTasks.add(task);
        if (task.isDeleted()) {
            Log.d(TAG, "merge2: was deleted " + task.title);
        }
    }
}

From source file:com.granita.icloudcalsync.resource.LocalCalendar.java

public static LocalCalendar[] findAll(Account account, ContentProviderClient providerClient)
        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<>();
    while (cursor != null && cursor.moveToNext())
        calendars.add(new LocalCalendar(account, providerClient, cursor.getInt(0), cursor.getString(1)));
    return calendars.toArray(new LocalCalendar[0]);
}

From source file:com.android.emailcommon.provider.Account.java

/**
 * Clear all account hold flags that are set.
 *
 * (This will trigger watchers, and in particular will cause EAS to try and resync the
 * account(s).)//  w w  w .  j av a  2  s .co m
 */
public static void clearSecurityHoldOnAllAccounts(Context context) {
    ContentResolver resolver = context.getContentResolver();
    Cursor c = resolver.query(Account.CONTENT_URI, ACCOUNT_FLAGS_PROJECTION, SECURITY_NONZERO_SELECTION, null,
            null);
    try {
        while (c.moveToNext()) {
            int flags = c.getInt(ACCOUNT_FLAGS_COLUMN_FLAGS);

            if (0 != (flags & FLAGS_SECURITY_HOLD)) {
                ContentValues cv = new ContentValues();
                cv.put(AccountColumns.FLAGS, flags & ~FLAGS_SECURITY_HOLD);
                long accountId = c.getLong(ACCOUNT_FLAGS_COLUMN_ID);
                Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
                resolver.update(uri, cv, null, null);
            }
        }
    } finally {
        c.close();
    }
}