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.raspi.chatapp.util.storage.MessageHistory.java

public int getMessageAmount(String buddyId) {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    try {//from w  w  w .jav a 2s  .com
        Cursor c = db.rawQuery("SELECT * FROM " + buddyId, null);
        int cnt = c.getCount();
        c.close();
        db.close();
        return cnt;
    } catch (Exception e) {
        return 0;
    }
}

From source file:com.seneca.android.senfitbeta.DbHelper.java

public ArrayList<Exercise> getExByMuscles(int num) {
    Log.d("SELECT EXDB", "Getinging exercise By id");

    String selectQuery = "SELECT * FROM exercises WHERE id LIKE '%" + num + "%' ORDER BY " + EXERCISE_ID
            + " ASC";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    cursor.moveToFirst();//  w  w  w  .j  a  v  a 2 s .  c  om

    if (cursor == null) {
        Log.d("exiting", "NOTHING");
    }

    if (cursor.getCount() == 0) {
        Log.d("NOTHING", "0 nothing");
    }

    ArrayList<Exercise> temp = new ArrayList<Exercise>();
    cursor.moveToFirst();
    do {
        Exercise ex = new Exercise();
        ex.setId(cursor.getInt(cursor.getColumnIndex(EXERCISE_ID)));
        ex.setLicense_author(cursor.getString(cursor.getColumnIndex(AUTHOR)));
        ex.setDescription(cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
        ex.setName(cursor.getString(cursor.getColumnIndex(NAMETYPE)));
        ex.setName_original(cursor.getString(cursor.getColumnIndex(ORIGNALNAME)));
        ex.setCreation_date(cursor.getString(cursor.getColumnIndex(CREATIONDATE)));
        ex.setCategory(cursor.getString(cursor.getColumnIndex(CATEGORY)));

        temp.add(ex);
    } while (cursor.moveToNext());

    cursor.close();
    getReadableDatabase().close();

    return temp;

}

From source file:com.tct.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
    mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY);
    mHtmlLinkifyParts = new SparseArray<String>(cursorSize);
    mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY);
    mTextLinkifyParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_S
        InputStream htmlIn = null;
        InputStream textIn = null;
        try {//from   w  ww .j  a  v  a  2  s  .  co m
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect,
                //such as fileNotFoundException,maybe the connection will not be closed. just a try!!!
                htmlIn = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(htmlIn);
                } finally {
                    htmlIn.close();
                    htmlIn = null;
                }
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for sanitized html
                if (!TextUtils.isEmpty(sanitizedHtml)) {
                    final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml);
                    mHtmlLinkifyParts.put(position, linkifyHtml);
                } else {
                    mHtmlLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d",
                    messageId);
            mHtmlLinkifyParts.put(position, "");
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                textIn = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(textIn);
                } finally {
                    textIn.close();
                    textIn = null;
                }
                mTextParts.put(position, underlyingTextString);
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for underlying text string
                if (!TextUtils.isEmpty(underlyingTextString)) {
                    final SpannableString spannable = new SpannableString(underlyingTextString);
                    Linkify.addLinks(spannable,
                            Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
                    final String linkifyText = Html.toHtml(spannable);
                    mTextLinkifyParts.put(position, linkifyText);
                } else {
                    mTextLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d",
                    messageId);
            mTextLinkifyParts.put(position, "");
        }
        //NOTE:Remember that this just a protective code,for better release Not used Resources.
        if (htmlIn != null) {
            try {
                htmlIn.close();
            } catch (IOException e1) {
                LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection ");
            }
        }
        if (textIn != null) {
            try {
                textIn.close();
            } catch (IOException e2) {
                LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection ");
            }
        } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_E
    }
    cursor.moveToPosition(-1);
}

From source file:com.jaspersoft.android.jaspermobile.activities.profile.ServerProfileActivity.java

@UiThread
protected void checkUniqueConstraintFulfilled(Cursor cursor) {
    boolean entryExists = cursor.getCount() > 0;
    getSupportLoaderManager().destroyLoader(QUERY_UNIQUENESS);

    if (entryExists) {
        aliasEdit.setError(getString(R.string.sp_error_duplicate_alias));
        aliasEdit.requestFocus();/*w  ww . jav a 2s  .  co  m*/

        Toast toast = Toast.makeText(this, getString(R.string.sp_error_unique_alias, alias),
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, mActionBarSize + (mActionBarSize / 2));
        toast.show();
    } else {
        JsServerProfile oldProfile = jsRestClient.getServerProfile();
        if (oldProfile != null && oldProfile.getId() == profileId) {
            updateServerProfile(oldProfile);
        } else {
            persistProfileData();
            setOkResult();
            finish();
        }

        hideKeyboard();
    }
}

From source file:com.android.server.MaybeDatabaseHelper.java

public boolean rowExists(String packagename) {
    Log.v(DBTAG, "rowExits:" + packagename);
    Cursor cursor = null;
    String selection = PACKAGE_COL + "='" + packagename + "'";
    boolean ret = false;
    try {//from   w w w.j a  v  a2  s . co  m
        cursor = sDatabase.query(APP_TABLE_NAME, null, selection, null, null, null, null, null);
        if (cursor.getCount() > 0) {
            ret = true;
        } else {
            ret = false;
        }

    } catch (IllegalStateException e) {
        Log.e(DBTAG, "getAppDataFromDB failed", e);
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return ret;
}

From source file:com.blandware.android.atleap.test.RobospiceTestCase.java

public void test_book_by_id() throws Exception {
    Book.BooksResult result = makeRobospiceRequest(BOOKS_FILENAME, new BooksAuthorsRobospiceRequest());

    Cursor cursor = getContext().getContentResolver().query(
            TestContract.Book.CONTENT_URI.buildUpon().appendPath("1382763").build(), //uri
            null, //projection
            null, //selection
            null, //selectionArgs
            null //sort order
    );/*from w ww  . j ava 2 s  .  c  o  m*/

    assertTrue(cursor != null);
    assertTrue(cursor.getCount() == 1);

    cursor.moveToFirst();

    assertTrue(cursor.getString(cursor.getColumnIndex(TestContract.Book.TITLE)) != null);
    assertTrue(cursor.getString(cursor.getColumnIndex(TestContract.Book.TITLE)).equals("Super book"));
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Read phone call log and update app database
 *//*from ww  w. j a  v a 2  s .  c  om*/
private void readCallLog() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
        Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null,
                CallLog.Calls.DATE + " DESC");

        int totalCalls = c.getCount();

        EventBus.getDefault()
                .post(new CallSyncEvent(SYNC_MESSAGE, "Reading phone log: " + c.getCount() + " calls..."));

        if (c.moveToFirst()) {
            for (int i = 0; i < totalCalls; i++) {
                EventBus.getDefault()
                        .post(new CallSyncEvent(SYNC_MESSAGE, "Local call " + i + "/" + totalCalls + "..."));
                String callerID = c.getString(c.getColumnIndex(CallLog.Calls._ID));
                String callerNumber = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
                long callDateandTime = c.getLong(c.getColumnIndex(CallLog.Calls.DATE));
                long callDuration = c.getLong(c.getColumnIndex(CallLog.Calls.DURATION));
                int callType = c.getInt(c.getColumnIndex(CallLog.Calls.TYPE));

                Call call = Call.getByIdNumberDate(callerID, callerNumber, callDateandTime);

                if (call == null) {
                    call = new Call();
                }

                call.setRemoteId(
                        (call.getRemoteId() != "" && call.getRemoteId() != null) ? call.getRemoteId() : "");
                call.setCallerId(callerID);
                call.setCallerNumber(callerNumber);
                call.setDateAndTime(DateUtils.formatDate(callDateandTime));
                call.setType(callType);
                call.setDuration(callDuration);

                boolean hasDevice = call.getDeviceId() != "" && call.getDeviceId() != null;

                call.setDeviceId(hasDevice ? call.getDeviceId() : Device.registeredDevice().getLogin());
                call.save();

                allCalls.add(call);

                c.moveToNext();
            }
        }
        c.close();
    } else {
        EventBus.getDefault()
                .post(new CallSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_call_log)));
    }
}

From source file:com.android.contacts.common.list.PhoneNumberPickerFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    super.onLoadFinished(loader, data);

    // disable scroll bar if there is no data
    setVisibleScrollbarEnabled(data != null && !data.isClosed() && data.getCount() > 0);
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

private static void addExtensionsToContactEntry(ContentResolver cr, long personId, ContactEntry entry)
        throws ParseException {
    Cursor c = cr.query(Extensions.CONTENT_URI, null, "person=" + personId, null, null);
    try {//w  w w. j  ava 2 s .co  m
        JSONObject jsonObject = new JSONObject();
        int nameIndex = c.getColumnIndexOrThrow(Extensions.NAME);
        int valueIndex = c.getColumnIndexOrThrow(Extensions.VALUE);
        if (c.getCount() == 0)
            return;
        while (c.moveToNext()) {
            try {
                jsonObject.put(c.getString(nameIndex), c.getString(valueIndex));
            } catch (JSONException e) {
                throw new ParseException("bad key or value", e);
            }
        }
        ExtendedProperty extendedProperty = new ExtendedProperty();
        extendedProperty.setName("android");
        final String jsonString = jsonObject.toString();
        if (jsonString == null) {
            throw new ParseException(
                    "unable to convert cursor into a JSON string, " + DatabaseUtils.dumpCursorToString(c));
        }
        extendedProperty.setXmlBlob(jsonString);
        entry.addExtendedProperty(extendedProperty);
    } finally {
        if (c != null)
            c.close();
    }
}

From source file:com.example.cmput301.model.DatabaseManager.java

/**
 * Gets a task (if exists) from the "local" table of the database.
 *
 * @param id ID of task to search for//from  w ww .j a va  2 s. co  m
 * @return Task found, if nothing found returns null.
 * @throws JSONException 
 */
public Task getLocalTask(String id) {
    try {
        Cursor c = db.rawQuery(
                "SELECT * FROM " + StringRes.LOCAL_TASK_TABLE_NAME + " WHERE " + StringRes.COL_ID + "=?",
                new String[] { id, });
        if (c == null || c.getCount() == 0) {
            return null;
        } else {
            c.moveToFirst();
            String string = c.getString(c.getColumnIndex(StringRes.COL_CONTENT));

            return toTask(getJsonTask(string));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;

}