Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

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

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:com.rsegismont.androlife.core.utils.AndrolifeUtils.java

public static long getTonightIndex(Cursor mCursor) {
    if (mCursor == null)
        return -1;

    if (mCursor.getCount() <= 0)
        return -1;

    long dateUtc = -1;

    final int initialPosition = mCursor.getPosition();

    mCursor.moveToPosition(0);//from  w  w  w  . j a  va  2s. c om

    final long initialValue = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));

    final Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(initialValue);
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    for (int i = 0; i < mCursor.getCount(); i++) {
        mCursor.moveToPosition(i);
        final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));

        if (calendar.getTime().getTime() - value < 0) {

            mCursor.moveToPosition(Math.max(0, i - 1));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
        if ((i == 0) && (calendar.getTime().getTime() - value < 0)) {

            mCursor.moveToPosition(0);
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if (i == (mCursor.getCount() - 1)) {

            mCursor.moveToPosition(Math.max(0, mCursor.getCount() - 1));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
    }

    if (initialPosition >= 0)
        mCursor.moveToPosition(initialPosition);

    return dateUtc;
}

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

public static Map<PublicScript, Date> geLastUpdates(Context context, String trollId,
        Set<PublicScript> scripts) {

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

    Map<PublicScript, Date> result = new HashMap<PublicScript, Date>();

    for (PublicScript script : scripts) {

        Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
                new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
        Date lastUpdate = null;//from  ww w .j  a  va 2 s  .  c om
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            long resultTimestamp = cursor.getLong(0);
            lastUpdate = new Date(resultTimestamp);
        }

        result.put(script, lastUpdate);
        cursor.close();
    }
    database.close();

    String format = "Last updates for troll=%s are: '%s'";
    String message = String.format(format, trollId, result);
    Log.i(TAG, message);

    return result;
}

From source file:com.rsegismont.androlife.core.utils.AndrolifeUtils.java

public static long getCurrentIndex(Cursor mCursor) {

    long dateUtc = -1;

    if (mCursor == null)
        return -1;

    if (mCursor.getCount() <= 0)
        return -1;

    final int initialPosition = mCursor.getPosition();

    int index = -1;

    for (int i = 0; i < mCursor.getCount(); i++) {
        mCursor.moveToPosition(i);//from  ww  w. j  a  va  2 s . com
        final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
        if (System.currentTimeMillis() - value < 0) {
            index = i - 1;
            mCursor.moveToPosition(Math.max(0, index));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if ((i == 0) && (System.currentTimeMillis() - value < 0)) {

            mCursor.moveToPosition(0);
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if (i == (mCursor.getCount() - 1)) {
            index = (mCursor.getCount() - 1);
            mCursor.moveToPosition(Math.max(0, index));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
    }

    if (initialPosition >= 0)
        mCursor.moveToPosition(initialPosition);
    return dateUtc;

}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

/**
 * Increments the usage counter for the given unit.
 * @param unit name of the unit//from w ww . j  av  a2 s  . c o  m
 * @param db the unit usage database
 */
public static void logUnitUsed(String unit, ContentResolver cr) {
    final String[] selectionArgs = { unit };
    final Cursor c = cr.query(UsageEntry.CONTENT_URI, INCREMENT_QUERY_PROJECTION, UsageEntry._UNIT + "=?",
            selectionArgs, null);
    if (c.getCount() > 0) {
        c.moveToFirst();
        final int useCount = c.getInt(c.getColumnIndex(UsageEntry._USE_COUNT));
        final int id = c.getInt(c.getColumnIndex(UsageEntry._ID));
        final ContentValues cv = new ContentValues();
        cv.put(UsageEntry._USE_COUNT, useCount + 1);

        cr.update(ContentUris.withAppendedId(UsageEntry.CONTENT_URI, id), cv, null, null);
    } else {
        final ContentValues cv = new ContentValues();
        cv.put(UsageEntry._UNIT, unit);
        cv.put(UsageEntry._USE_COUNT, 1);
        cv.put(UsageEntry._FACTOR_FPRINT, getFingerprint(unit));
        cr.insert(UsageEntry.CONTENT_URI, cv);
    }
    c.close();
}

From source file:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * @param v the view to bind/*w  ww  .ja va  2 s .  c om*/
 * @param context standard activity context
 * @param c the cursor source for the object in the db object table.
 * Must include _id in the projection.
 * 
 * @param allowInteractions controls whether the bound view is
 * allowed to intercept touch events and do its own processing.
 */
public static void bindView(View v, final Context context, Cursor cursor, boolean allowInteractions) {
    TextView nameText = (TextView) v.findViewById(R.id.name_text);
    ViewGroup frame = (ViewGroup) v.findViewById(R.id.object_content);
    frame.removeAllViews();

    // make sure we have all the columns we need
    Long objId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
    String[] projection = null;
    String selection = DbObj.COL_ID + " = ?";
    String[] selectionArgs = new String[] { Long.toString(objId) };
    String sortOrder = null;
    Cursor c = context.getContentResolver().query(DbObj.OBJ_URI, projection, selection, selectionArgs,
            sortOrder);
    if (!c.moveToFirst()) {
        Log.w(TAG, "could not find obj " + objId);
        c.close();
        return;
    }
    DbObj obj = App.instance().getMusubi().objForCursor(c);
    if (obj == null) {
        nameText.setText("Failed to access database.");
        Log.e("DbObject", "cursor was null for bindView of DbObject");
        return;
    }
    DbUser sender = obj.getSender();
    Long timestamp = c.getLong(c.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
    Long hash = obj.getHash();
    short deleted = c.getShort(c.getColumnIndexOrThrow(DELETED));
    String feedName = obj.getFeedName();
    String type = obj.getType();
    Date date = new Date(timestamp);
    c.close();
    c = null;

    if (sender == null) {
        nameText.setText("Message from unknown contact.");
        return;
    }
    nameText.setText(sender.getName());

    final ImageView icon = (ImageView) v.findViewById(R.id.icon);
    if (sViewProfileAction == null) {
        sViewProfileAction = new OnClickViewProfile((Activity) context);
    }
    icon.setTag(sender.getLocalId());
    if (allowInteractions) {
        icon.setOnClickListener(sViewProfileAction);
        v.setTag(objId);
    }
    icon.setImageBitmap(sender.getPicture());

    if (deleted == 1) {
        v.setBackgroundColor(sDeletedColor);
    } else {
        v.setBackgroundColor(Color.TRANSPARENT);
    }

    TextView timeText = (TextView) v.findViewById(R.id.time_text);
    timeText.setText(RelativeDate.getRelativeDate(date));

    frame.setTag(objId); // TODO: error prone! This is database id
    frame.setTag(R.id.object_entry, cursor.getPosition()); // this is cursor id
    FeedRenderer renderer = DbObjects.getFeedRenderer(type);
    if (renderer != null) {
        renderer.render(context, frame, obj, allowInteractions);
    }

    if (!allowInteractions) {
        v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
        v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
    } else {
        if (!MusubiBaseActivity.isDeveloperModeEnabled(context)) {
            v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
            v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
        } else {
            ImageView attachmentCountButton = (ImageView) v.findViewById(R.id.obj_attachments_icon);
            TextView attachmentCountText = (TextView) v.findViewById(R.id.obj_attachments);
            attachmentCountButton.setVisibility(View.VISIBLE);

            if (hash == 0) {
                attachmentCountButton.setVisibility(View.GONE);
            } else {
                //int color = DbObject.colorFor(hash);
                boolean selfPost = false;
                DBHelper helper = new DBHelper(context);
                try {
                    Cursor attachments = obj.getSubfeed().query("type=?", new String[] { LikeObj.TYPE });
                    try {
                        attachmentCountText.setText("+" + attachments.getCount());

                        if (attachments.moveToFirst()) {
                            while (!attachments.isAfterLast()) {
                                if (attachments.getInt(attachments.getColumnIndex(CONTACT_ID)) == -666) {
                                    selfPost = true;
                                    break;
                                }
                                attachments.moveToNext();

                            }
                        }
                    } finally {
                        attachments.close();
                    }
                } finally {
                    helper.close();
                }
                if (selfPost) {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love_red);
                } else {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love);
                }
                attachmentCountText.setTag(R.id.object_entry, hash);
                attachmentCountText.setTag(R.id.feed_label, Feed.uriForName(feedName));
                attachmentCountText.setOnClickListener(LikeListener.getInstance(context));
            }
        }
    }
}

From source file:foam.zizim.android.BoskoiService.java

public static CategoriesData[] getParentCategories() {
    Cursor cursor = BoskoiApplication.mDb.fetchParentCategories();
    CategoriesData result[] = new CategoriesData[cursor.getCount()];

    int i = 0;//  ww  w.j  a va 2  s. c o  m
    if (cursor.moveToFirst()) {
        int titleIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE);
        int titleNL = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_NL);
        int titleLA = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_LA);
        int idIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_ID);
        int parentId = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_PARENT_ID);
        int color = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_COLOR);
        int desc = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_DESC);

        do {
            CategoriesData cat = new CategoriesData();
            cat.setCategoryId(cursor.getInt(idIndex));
            cat.setCategoryTitle(cursor.getString(titleIndex));
            cat.setCategoryTitleNL(cursor.getString(titleNL));
            cat.setCategoryTitleLA(cursor.getString(titleLA));
            cat.setCategoryParentId(cursor.getInt(parentId));
            cat.setCategoryColor(cursor.getString(color));
            cat.setCategoryDescription(cursor.getString(desc));

            result[i] = cat;

            i++;
        } while (cursor.moveToNext());
    }

    cursor.close();
    return result;
}

From source file:com.android.emailcommon.internet.Rfc822Output.java

/**
 * Write the entire message to an output stream.  This method provides buffering, so it is
 * not necessary to pass in a buffered output stream here.
 *
 * @param context system context for accessing the provider
 * @param messageId the message to write out
 * @param out the output stream to write the message to
 * @param useSmartReply whether or not quoted text is appended to a reply/forward
 *//*w ww. ja  v  a2s .c o  m*/
public static void writeTo(Context context, long messageId, OutputStream out, boolean useSmartReply,
        boolean sendBcc) throws IOException, MessagingException {
    Message message = Message.restoreMessageWithId(context, messageId);
    if (message == null) {
        // throw something?
        return;
    }

    OutputStream stream = new BufferedOutputStream(out, 1024);
    Writer writer = new OutputStreamWriter(stream);

    // Write the fixed headers.  Ordering is arbitrary (the legacy code iterated through a
    // hashmap here).

    String date = DATE_FORMAT.format(new Date(message.mTimeStamp));
    writeHeader(writer, "Date", date);

    writeEncodedHeader(writer, "Subject", message.mSubject);

    writeHeader(writer, "Message-ID", message.mMessageId);

    writeAddressHeader(writer, "From", message.mFrom);
    writeAddressHeader(writer, "To", message.mTo);
    writeAddressHeader(writer, "Cc", message.mCc);
    // Address fields.  Note that we skip bcc unless the sendBcc argument is true
    // SMTP should NOT send bcc headers, but EAS must send it!
    if (sendBcc) {
        writeAddressHeader(writer, "Bcc", message.mBcc);
    }
    writeAddressHeader(writer, "Reply-To", message.mReplyTo);
    writeHeader(writer, "MIME-Version", "1.0");

    // Analyze message and determine if we have multiparts
    Body body = Body.restoreBodyWithMessageId(context, message.mId);
    String[] bodyText = buildBodyText(body, message.mFlags, useSmartReply);

    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION,
            WHERE_NOT_SMART_FORWARD, null, null);

    try {
        int attachmentCount = attachmentsCursor.getCount();
        boolean multipart = attachmentCount > 0;
        String multipartBoundary = null;
        String multipartType = "mixed";

        // Simplified case for no multipart - just emit text and be done.
        if (!multipart) {
            writeTextWithHeaders(writer, stream, bodyText);
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = getNextBoundary();

            // Move to the first attachment; this must succeed because multipart is true
            attachmentsCursor.moveToFirst();
            if (attachmentCount == 1) {
                // If we've got one attachment and it's an ics "attachment", we want to send
                // this as multipart/alternative instead of multipart/mixed
                int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
                if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
                    multipartType = "alternative";
                }
            }

            writeHeader(writer, "Content-Type",
                    "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");

            // first multipart element is the body
            if (bodyText[INDEX_BODY_TEXT] != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, bodyText);
            }

            // Write out the attachments until we run out
            do {
                writeBoundary(writer, multipartBoundary, false);
                Attachment attachment = Attachment.getContent(attachmentsCursor, Attachment.class);
                writeOneAttachment(context, writer, stream, attachment);
                writer.write("\r\n");
            } while (attachmentsCursor.moveToNext());

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    } finally {
        attachmentsCursor.close();
    }

    writer.flush();
    out.flush();
}

From source file:foam.zizim.android.BoskoiService.java

public static CategoriesData[] getCategoriesFromParent(int categoryId) {
    Cursor cursor = BoskoiApplication.mDb.fetchCategoriesFromParent(categoryId);
    CategoriesData result[] = new CategoriesData[cursor.getCount()];

    int i = 0;//from   w w w . j a  va2s  .c  om
    if (cursor.moveToFirst()) {
        int titleIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE);
        int titleNL = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_NL);
        int titleLA = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_LA);
        int idIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_ID);
        int parentId = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_PARENT_ID);
        int color = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_COLOR);
        int desc = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_DESC);

        do {
            CategoriesData cat = new CategoriesData();
            cat.setCategoryId(cursor.getInt(idIndex));
            cat.setCategoryTitle(cursor.getString(titleIndex));
            cat.setCategoryTitleNL(cursor.getString(titleNL));
            cat.setCategoryTitleLA(cursor.getString(titleLA));
            cat.setCategoryParentId(cursor.getInt(parentId));
            cat.setCategoryColor(cursor.getString(color));
            cat.setCategoryDescription(cursor.getString(desc));

            result[i] = cat;

            i++;
        } while (cursor.moveToNext());
    }

    cursor.close();
    return result;
}

From source file:Main.java

private static String makeTitle(Cursor result, String packageName, String extNumber) {
    String title = "";
    String prefValue = mPreferences.getString("ext_title_preference" + extNumber, "app_count");
    // App name, no count
    if (prefValue.equals(mPrefValues[0])) {
        try {//w w  w .  j  av  a 2  s .c  o m
            title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString();
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    // App name with count
    else if (prefValue.equals(mPrefValues[1])) {
        int count = result.getCount() == 0 ? 0 : result.getInt(10);
        try {
            title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString() + " ("
                    + Integer.toString(count) + ")";
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    // Custom, no count
    else if (prefValue.equals(mPrefValues[2])) {
        try {
            String temp = mPreferences.getString("text_preference" + extNumber, "");
            if (TextUtils.isEmpty(temp))
                title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString();
            else
                title = temp;

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    // Custom with count
    else if (prefValue.equals(mPrefValues[3])) {
        int count = result.getCount() == 0 ? 0 : result.getInt(10);
        try {
            String temp = mPreferences.getString("text_preference" + extNumber, "");
            if (TextUtils.isEmpty(temp))
                title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString() + " ("
                        + Integer.toString(count) + ")";
            else
                title = temp + " (" + Integer.toString(count) + ")";

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    // Notification title, no count
    else if (prefValue.equals(mPrefValues[4])) {
        try {
            title = result.getString(3);
        } catch (CursorIndexOutOfBoundsException e) {
            try {
                title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString();
            } catch (NameNotFoundException e1) {
                e1.printStackTrace();
            }
        }
    }

    // Notification title with count
    else if (prefValue.equals(mPrefValues[5])) {
        int count = result.getCount() == 0 ? 0 : result.getInt(10);
        try {
            title = result.getString(3) + " (" + Integer.toString(count) + ")";
        } catch (CursorIndexOutOfBoundsException e) {
            try {
                title = mPm.getApplicationLabel(mPm.getApplicationInfo(packageName, 0)).toString() + " ("
                        + Integer.toString(count) + ")";
            } catch (NameNotFoundException e1) {
                e1.printStackTrace();
            }
        }

    }

    result.moveToFirst();
    return title;

}

From source file:com.onesignal.NotificationOpenedProcessor.java

private static void updateSummaryNotification(SQLiteDatabase writableDb) {
    String grpId = intent.getStringExtra("grp");

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME,
            new String[] { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID }, // retColumn
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0 AND " + NotificationTable.COLUMN_NAME_IS_SUMMARY + " = 0",
            new String[] { grpId }, // whereArgs
            null, null, null);/*from  w  w  w . j a  v a2  s .c  om*/

    // All individual notifications consumed, make summary notification as consumed as well.
    if (cursor.getCount() == 0)
        writableDb.update(NotificationTable.TABLE_NAME, newContentValuesWithConsumed(),
                NotificationTable.COLUMN_NAME_GROUP_ID + " = ?", new String[] { grpId });
    else {
        try {
            GenerateNotification.createSummaryNotification(context, true,
                    new JSONObject("{\"grp\": \"" + grpId + "\"}"));
        } catch (JSONException e) {
        }
    }

    cursor.close();
}