Example usage for android.database Cursor isAfterLast

List of usage examples for android.database Cursor isAfterLast

Introduction

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

Prototype

boolean isAfterLast();

Source Link

Document

Returns whether the cursor is pointing to the position after the last row.

Usage

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

public static List<ParcelableAccount> getAccountsList(final Context context, final boolean activatedOnly,
        final boolean officialKeyOnly) {
    if (context == null)
        return Collections.emptyList();
    final ArrayList<ParcelableAccount> accounts = new ArrayList<>();
    final String selection = activatedOnly ? Accounts.IS_ACTIVATED + " = 1" : null;
    final Cursor cur = context.getContentResolver().query(Accounts.CONTENT_URI, Accounts.COLUMNS, selection,
            null, Accounts.SORT_POSITION);
    if (cur == null)
        return accounts;
    final ParcelableCredentialsCursorIndices indices = new ParcelableCredentialsCursorIndices(cur);
    cur.moveToFirst();//from www.  j a  v a  2 s .c  o  m
    while (!cur.isAfterLast()) {
        if (!officialKeyOnly) {
            accounts.add(indices.newObject(cur));
        } else {
            final String consumerKey = cur.getString(indices.consumer_key);
            final String consumerSecret = cur.getString(indices.consumer_secret);
            if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) {
                accounts.add(indices.newObject(cur));
            }
        }
        cur.moveToNext();
    }
    cur.close();
    return accounts;
}

From source file:com.money.manager.ex.notifications.RepeatingTransactionNotifications.java

public void notifyRepeatingTransaction() {
    // create application
    CurrencyUtils currencyUtils = new CurrencyUtils(context);
    // init currencies
    if (!currencyUtils.isInit())
        currencyUtils.init();//w w  w.  ja va  2 s  . com

    // select data
    QueryBillDeposits billDeposits = new QueryBillDeposits(context);
    MoneyManagerOpenHelper databaseHelper = new MoneyManagerOpenHelper(context);

    if (databaseHelper != null) {
        Cursor cursor = databaseHelper.getReadableDatabase().rawQuery(billDeposits.getSource() + " AND "
                + QueryBillDeposits.DAYSLEFT + "<=0 ORDER BY " + QueryBillDeposits.NEXTOCCURRENCEDATE, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
                while (!cursor.isAfterLast()) {
                    String line = cursor
                            .getString(cursor.getColumnIndex(QueryBillDeposits.USERNEXTOCCURRENCEDATE)) + " "
                            + cursor.getString(cursor.getColumnIndex(QueryBillDeposits.PAYEENAME)) + ": <b>"
                            + currencyUtils.getCurrencyFormatted(
                                    cursor.getInt(cursor.getColumnIndex(QueryBillDeposits.CURRENCYID)),
                                    cursor.getDouble(cursor.getColumnIndex(QueryBillDeposits.AMOUNT)))
                            + "</b>";
                    // add line
                    inboxStyle.addLine(Html.fromHtml("<small>" + line + "</small>"));
                    // move to next row
                    cursor.moveToNext();
                }

                NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                // create pendig intent
                Intent intent = new Intent(context, RepeatingTransactionListActivity.class);
                // set launch from notification // check pin code
                intent.putExtra(RepeatingTransactionListActivity.INTENT_EXTRA_LAUNCH_NOTIFICATION, true);

                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
                // create notification
                Notification notification = null;
                try {
                    notification = new NotificationCompat.Builder(context).setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .setContentTitle(context.getString(R.string.application_name))
                            .setContentText(
                                    context.getString(R.string.notification_repeating_transaction_expired))
                            .setSubText(context
                                    .getString(R.string.notification_click_to_check_repeating_transaction))
                            .setSmallIcon(R.drawable.ic_stat_notification)
                            .setTicker(context.getString(R.string.notification_repeating_transaction_expired))
                            .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND
                                    | Notification.DEFAULT_LIGHTS)
                            .setNumber(cursor.getCount()).setStyle(inboxStyle).build();
                    // notify 
                    notificationManager.cancel(ID_NOTIFICATION);
                    notificationManager.notify(ID_NOTIFICATION, notification);
                } catch (Exception e) {
                    Log.e(LOGCAT, e.getMessage());
                }
            }
            // close cursor
            cursor.close();
        }
        // close database helper
        //databaseHelper.close();
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

private static int getFirstId(Cursor cursor, int id) {
    if (cursor != null) {
        cursor.moveToFirst();/* www.  j  a  v  a 2s.  co  m*/
        if (!cursor.isAfterLast()) {
            id = cursor.getInt(0);
        }
        cursor.close();
    }
    return id;
}

From source file:gov.wa.wsdot.android.wsdot.service.FerriesTerminalSailingSpaceSyncService.java

/** 
 * Check the ferries terminal space sailing table for any starred entries.
 * If we find some, save them to a list so we can re-star those after we
 * flush the database.//from  ww w .  j  a  v a 2  s . com
 */
private List<Integer> getStarred() {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    List<Integer> starred = new ArrayList<Integer>();

    try {
        cursor = resolver.query(FerriesTerminalSailingSpace.CONTENT_URI,
                new String[] { FerriesTerminalSailingSpace.TERMINAL_ID },
                FerriesTerminalSailingSpace.TERMINAL_IS_STARRED + "=?", new String[] { "1" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                starred.add(cursor.getInt(0));
                cursor.moveToNext();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return starred;
}

From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserBookmarksDataAccessor.java

public void checkAndBuildSpecialGuids() throws NullCursorException {
    final String[] specialGUIDs = AndroidBrowserBookmarksRepositorySession.SPECIAL_GUIDS;
    Cursor cur = fetch(specialGUIDs);
    long mobileRoot = 0;
    long desktopRoot = 0;

    // Map from GUID to whether deleted. Non-presence implies just that.
    HashMap<String, Boolean> statuses = new HashMap<String, Boolean>(specialGUIDs.length);
    try {//from  w  ww  .  j a  va 2 s  . c o m
        if (cur.moveToFirst()) {
            while (!cur.isAfterLast()) {
                String guid = RepoUtils.getStringFromCursor(cur, BrowserContract.SyncColumns.GUID);
                if (guid.equals("mobile")) {
                    mobileRoot = RepoUtils.getLongFromCursor(cur, BrowserContract.CommonColumns._ID);
                }
                if (guid.equals("desktop")) {
                    desktopRoot = RepoUtils.getLongFromCursor(cur, BrowserContract.CommonColumns._ID);
                }
                // Make sure none of these folders are marked as deleted.
                boolean deleted = RepoUtils.getLongFromCursor(cur, BrowserContract.SyncColumns.IS_DELETED) == 1;
                statuses.put(guid, deleted);
                cur.moveToNext();
            }
        }
    } finally {
        cur.close();
    }

    // Insert or undelete them if missing.
    for (String guid : specialGUIDs) {
        if (statuses.containsKey(guid)) {
            if (statuses.get(guid)) {
                // Undelete.
                Logger.info(LOG_TAG, "Undeleting special GUID " + guid);
                ContentValues cv = new ContentValues();
                cv.put(BrowserContract.SyncColumns.IS_DELETED, 0);
                updateByGuid(guid, cv);
            }
        } else {
            // Insert.
            if (guid.equals("mobile")) {
                Logger.info(LOG_TAG, "No mobile folder. Inserting one.");
                mobileRoot = insertSpecialFolder("mobile", 0);
            } else if (guid.equals("places")) {
                // This is awkward.
                Logger.info(LOG_TAG, "No places root. Inserting one under mobile (" + mobileRoot + ").");
                desktopRoot = insertSpecialFolder("places", mobileRoot);
            } else {
                // unfiled, menu, toolbar.
                Logger.info(LOG_TAG, "No " + guid + " root. Inserting one under places (" + desktopRoot + ").");
                insertSpecialFolder(guid, desktopRoot);
            }
        }
    }
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {//from  ww  w . j  a  v a 2s  .com
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:edu.pdx.cecs.orcycle.NoteUploader.java

@Override
protected Boolean doInBackground(Long... noteIds) {
    // First, send the note user asked for:
    Boolean result = true;//from   ww w  .  j a v a 2  s  .co  m
    if (noteIds.length != 0) {
        result = uploadOneNote(noteIds[0]);
    }

    // Then, automatically try and send previously-completed notes
    // that were not sent successfully.
    Vector<Long> unsentNotes = new Vector<Long>();

    mDb.openReadOnly();
    Cursor cur = mDb.fetchUnsentNotes();
    if (cur != null && cur.getCount() > 0) {
        // pd.setMessage("Sent. You have previously unsent notes; submitting those now.");
        while (!cur.isAfterLast()) {
            unsentNotes.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long note : unsentNotes) {
        result &= uploadOneNote(note);
    }
    return result;
}

From source file:com.digipom.manteresting.android.processor.json.NailsJsonProcessor.java

@Override
public ArrayList<ContentProviderOperation> parse(JSONObject response, Meta meta) throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final TreeSet<Integer> nailIds = new TreeSet<Integer>();
    final Cursor nails = resolver.query(ManterestingContract.Nails.CONTENT_URI, new String[] { Nails.NAIL_ID },
            null, null, Nails.NAIL_ID + " DESC");
    int greatestOfExisting = Integer.MIN_VALUE;

    if (nails != null && !nails.isClosed()) {
        try {/*from ww  w . j  av  a  2s  .  c o m*/
            nails.moveToFirst();

            final int idColumn = nails.getColumnIndex(Nails.NAIL_ID);

            while (!nails.isAfterLast()) {
                final int nailId = nails.getInt(idColumn);
                nailIds.add(nailId);
                greatestOfExisting = nailId > greatestOfExisting ? nailId : greatestOfExisting;
                nails.moveToNext();
            }
        } finally {
            if (nails != null) {
                nails.close();
            }
        }
    }

    final JSONArray objects = response.getJSONArray("objects");
    int smallestOfNew = Integer.MAX_VALUE;

    for (int i = 0; i < objects.length(); i++) {
        final JSONObject nailObject = objects.getJSONObject(i);

        final boolean isPrivate = nailObject.getJSONObject("workbench").getBoolean("private");

        if (!isPrivate) {
            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Nails.CONTENT_URI);
            final int nailId = nailObject.getInt("id");
            smallestOfNew = nailId < smallestOfNew ? nailId : smallestOfNew;

            builder.withValue(Nails.NAIL_ID, nailId);
            builder.withValue(Nails.NAIL_JSON, nailObject.toString());

            batch.add(builder.build());
            nailIds.add(nailId);
        }
    }

    // If more than LIMIT were fetched, and this was the initial fetch, then
    // we flush everything in the DB before adding the new nails (as
    // otherwise we would introduce a gap).
    if (meta.nextOffset == meta.nextLimit // For initial fetch
            && smallestOfNew > greatestOfExisting) {
        if (LoggerConfig.canLog(Log.DEBUG)) {
            Log.d(TAG, "Flushing all existing nails on initial fetch, so as to avoid a gap.");
        }

        resolver.delete(Nails.CONTENT_URI, null, null);
    } else {
        // If more than 500 nails, find the 500th biggest and delete those
        // after it.
        if (nailIds.size() > MAX_COUNT) {
            Iterator<Integer> it = nailIds.descendingIterator();

            for (int i = 0; i < MAX_COUNT; i++) {
                it.next();
            }

            final Integer toDelete = it.next();

            if (LoggerConfig.canLog(Log.DEBUG)) {
                Log.d(TAG, "deleting from nails where NAIL_ID is less than or equal to " + toDelete);
            }

            SelectionBuilder selectionBuilder = new SelectionBuilder();
            selectionBuilder.where(ManterestingContract.Nails.NAIL_ID + " <= ?",
                    new String[] { String.valueOf(toDelete) });
            resolver.delete(ManterestingContract.Nails.CONTENT_URI, selectionBuilder.getSelection(),
                    selectionBuilder.getSelectionArgs());
        }
    }

    return batch;
}

From source file:com.andrew.apollo.menu.PlaylistDialog.java

private int idForplaylist(String name) {

    Cursor cursor = MusicUtils.query(this, Audio.Playlists.EXTERNAL_CONTENT_URI,
            new String[] { Audio.Playlists._ID }, Audio.Playlists.NAME + "=?", new String[] { name },
            Audio.Playlists.NAME, 0);/* ww  w  . j  a  va 2  s .  co  m*/
    int id = -1;
    if (cursor != null) {
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            id = cursor.getInt(0);
        }
        cursor.close();
    }

    return id;
}

From source file:net.peterkuterna.android.apps.devoxxfrsched.ui.tablet.TracksDropdownFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
    if (getActivity() != null) {
        // If there was a last-opened track, load it. Otherwise load the
        // first/*from w  ww .  j a v  a 2 s  .  c  o  m*/
        // track.
        data.moveToFirst();
        String lastTrackID = UIUtils.getLastUsedTrackID(getActivity());
        if (lastTrackID != null) {
            while (!data.isAfterLast()) {
                if (lastTrackID.equals(data.getString(TracksAdapter.TracksQuery.TRACK_ID))) {
                    break;
                }
                data.moveToNext();
            }

            if (data.isAfterLast()) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        loadTrack(null, mAutoloadTarget);
                    }
                });
            } else {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        loadTrack(data, mAutoloadTarget);
                    }
                });
            }
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    loadTrack(null, mAutoloadTarget);
                }
            });
        }
    }

    mAdapter.swapCursor(data);
}