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:io.v.android.apps.syncslides.SignInActivity.java

private void fetchUserNameFromContacts() {
    // Get the user's full name from Contacts.
    Cursor c = getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
    String[] columnNames = c.getColumnNames();
    String userName = "Anonymous User";
    while (c.moveToNext()) {
        for (int j = 0; j < columnNames.length; j++) {
            String columnName = columnNames[j];
            if (!columnName.equals(ContactsContract.Contacts.DISPLAY_NAME)) {
                continue;
            }//from w  w w  .j  av a  2  s  .co  m
            userName = c.getString(c.getColumnIndex(columnName));
        }
    }
    c.close();
    SharedPreferences.Editor editor = mPrefs.edit();
    editor.putString(PREF_USER_NAME_FROM_CONTACTS, userName);
    editor.commit();
}

From source file:com.navjagpal.fileshare.StreamingZipEntity.java

public void writeTo(OutputStream out) throws IOException {
    Cursor c = mContentResolver.query(FileSharingProvider.Files.CONTENT_URI,
            new String[] { FileSharingProvider.Files.Columns.DISPLAY_NAME,
                    FileSharingProvider.Files.Columns._DATA },
            FileSharingProvider.Files.Columns.FOLDER_ID + "=?", new String[] { mFolderId }, null);
    ZipOutputStream zipOut = new ZipOutputStream(out);
    byte[] buf = new byte[BUFFER_SIZE];
    while (c.moveToNext()) {
        String filename = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns.DISPLAY_NAME));
        String data = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns._DATA));
        zipOut.putNextEntry(new ZipEntry(filename));
        InputStream input = mContentResolver.openInputStream(Uri.parse(data));
        int len;// w  w w  .ja  va  2  s .co m
        while ((len = input.read(buf)) > 0) {
            zipOut.write(buf, 0, len);
        }
        zipOut.closeEntry();
        input.close();
    }
    zipOut.finish();
    mFinished = true;
}

From source file:com.ichi2.libanki.Tags.java

/** Add any missing tags from notes to the tags list. */
public void registerNotes(long[] nids) {
    // when called with a null argument, the old list is cleared first.
    String lim;/*from w w  w  .j  av  a2  s. c o  m*/
    if (nids != null) {
        lim = " WHERE id IN " + Utils.ids2str(nids);
    } else {
        lim = "";
        mTags.clear();
        mChanged = true;
    }
    List<String> tags = new ArrayList<String>();
    Cursor cursor = null;
    try {
        cursor = mCol.getDb().getDatabase().rawQuery("SELECT DISTINCT tags FROM notes" + lim, null);
        while (cursor.moveToNext()) {
            tags.add(cursor.getString(0));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    HashSet<String> tagSet = new HashSet<String>();
    for (String s : split(TextUtils.join(" ", tags))) {
        tagSet.add(s);
    }
    register(tagSet);
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//from   w w w  .  j a  va 2  s  .c o  m
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:com.android.transmart.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//from  w  w  w .  ja v a  2 s .co  m
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(LocationConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(LocationConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(LocationConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(LocationConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + LocationConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

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

/**
 * Return the id of the default account. If one hasn't been explicitly specified, return the
 * first one in the database. If no account exists, returns {@link #NO_ACCOUNT}.
 *
 * @param context the caller's context/*from   w ww.  ja v a  2s . c  o  m*/
 * @param lastUsedAccountId the last used account id, which is the basis of the default account
 */
public static long getDefaultAccountId(final Context context, final long lastUsedAccountId) {
    final Cursor cursor = context.getContentResolver().query(CONTENT_URI, ID_PROJECTION, null, null, null);

    long firstAccount = NO_ACCOUNT;

    try {
        if (cursor != null && cursor.moveToFirst()) {
            do {
                final long accountId = cursor.getLong(Account.ID_PROJECTION_COLUMN);

                if (accountId == lastUsedAccountId) {
                    return accountId;
                }

                if (firstAccount == NO_ACCOUNT) {
                    firstAccount = accountId;
                }
            } while (cursor.moveToNext());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return firstAccount;
}

From source file:com.money.manager.ex.datalayer.StockRepository.java

/**
 * Retrieves all record ids which refer the given symbol.
 * @return array of ids of records which contain the symbol.
 *///from  w  w  w .ja v  a 2s .  co  m
public int[] findIdsBySymbol(String symbol) {
    int[] result;

    Cursor cursor = getContext().getContentResolver().query(this.getUri(), new String[] { StockFields.STOCKID },
            StockFields.SYMBOL + "=?", new String[] { symbol }, null);
    if (cursor == null)
        return null;

    int records = cursor.getCount();
    result = new int[records];

    for (int i = 0; i < records; i++) {
        cursor.moveToNext();
        result[i] = cursor.getInt(cursor.getColumnIndex(StockFields.STOCKID));
    }
    cursor.close();

    return result;
}

From source file:com.amazonaws.mobileconnectors.pinpoint.internal.event.EventRecorder.java

public Uri recordEvent(final AnalyticsEvent event) {
    if (event != null) {
        log.info(String.format("Event Recorded to database with EventType: %s",
                StringUtil.clipString(event.getEventType(), CLIPPED_EVENT_LENGTH, true)));
    }/*w  w  w  . jav  a 2s . c  o  m*/
    long maxPendingSize = pinpointContext.getConfiguration().optLong(KEY_MAX_PENDING_SIZE,
            DEFAULT_MAX_PENDING_SIZE);
    if (maxPendingSize < MINIMUM_PENDING_SIZE) {
        maxPendingSize = MINIMUM_PENDING_SIZE;
    }

    final Uri uri = this.dbUtil.saveEvent(event);
    if (uri != null) {
        while (this.dbUtil.getTotalSize() > maxPendingSize) {
            Cursor cursor = null;
            try {
                cursor = this.dbUtil.queryOldestEvents(5);
                while (this.dbUtil.getTotalSize() > maxPendingSize && cursor.moveToNext()) {
                    this.dbUtil.deleteEvent(cursor.getInt(EventTable.COLUMN_INDEX.ID.getValue()),
                            cursor.getInt(EventTable.COLUMN_INDEX.SIZE.getValue()));
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }

        return uri;
    } else {
        log.warn(String.format("Event: '%s' failed to record to local database.",
                StringUtil.clipString(event.getEventType(), CLIPPED_EVENT_LENGTH, true)));
        return null;
    }
}

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

private boolean SendAllSegments() {

    boolean result = true;

    Vector<Long> unsentSegmentIds = new Vector<Long>();

    mDb.openReadOnly();/*from  ww  w.ja  v  a2 s .c om*/
    try {
        Cursor cursor = mDb.fetchUnsentSegmentIds();
        try {
            if (cursor != null && cursor.getCount() > 0) {
                // pd.setMessage("Sent. You have previously unsent notes; submitting those now.");
                while (!cursor.isAfterLast()) {
                    unsentSegmentIds.add(Long.valueOf(cursor.getLong(0)));
                    cursor.moveToNext();
                }
            }
        } finally {
            cursor.close();
        }
    } finally {
        mDb.close();
    }

    for (Long segmentId : unsentSegmentIds) {
        result &= uploadOneSegment(segmentId);
    }
    return result;

}

From source file:com.intel.xdk.contacts.Contacts.java

@SuppressWarnings("deprecation")
public void contactsChooserActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {
        Cursor cursor = activity.managedQuery(intent.getData(), null, null, null, null);
        cursor.moveToNext();
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

        getAllContacts();/* w  w  w  .j  a va  2s .  co m*/
        String js = String.format(
                " var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                contactId);
        injectJS("javascript:" + js);
        busy = false;
    } else {
        String js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=false;e.message='User canceled';document.dispatchEvent(e);";
        injectJS("javascript:" + js);
        busy = false;
    }

}