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.clearcenter.mobile_demo.mdStatusActivity.java

public void updateData() {
    JSONObject json_data;/*from  w w  w  .  jav a2  s  .  com*/

    String projection[] = new String[] { mdDeviceSamples.DATA };

    Cursor cursor = getContentResolver().query(mdDeviceSamples.CONTENT_URI, projection,
            mdDeviceSamples.NICKNAME + " = ?", new String[] { account_nickname }, null);

    int rows = 0;
    try {
        rows = cursor.getCount();
    } catch (NullPointerException e) {
    }

    Log.d(TAG, "Matches: " + rows);

    if (rows == 0) {
        Log.d(TAG, "No rows match for nickname: " + account_nickname);
        cursor.close();
        return;
    }

    cursor.moveToLast();

    String data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

    try {
        json_data = new JSONObject(data);
        if (json_data.has("hostname"))
            hostname_textview.setText("Hostname: " + json_data.getString("hostname"));
        if (json_data.has("name") && json_data.has("release")) {
            final String release = json_data.getString("name") + " " + json_data.getString("release");
            release_textview.setText("Release: " + release);
        }
        if (json_data.has("time_locale")) {
            time_textview.setText("Clock: " + json_data.getString("time_locale"));
        }

        if (rows >= 2) {
            bw_graphview.reset();
            loadavg_graphview.reset();
            mem_graphview.reset();

            if (rows <= samples)
                cursor.moveToFirst();
            else
                cursor.move(-samples);

            long unix_time = 0;
            double bw_up = 0.0;
            double bw_down = 0.0;

            do {
                data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

                final List<JSONObject> samples = sortedSamplesList(data);
                ListIterator<JSONObject> li = samples.listIterator();

                while (li.hasNext()) {
                    json_data = li.next();

                    if (unix_time == 0) {
                        bw_up = json_data.getDouble("bandwidth_up");
                        bw_down = json_data.getDouble("bandwidth_down");
                        unix_time = Long.valueOf(json_data.getString("time"));
                        continue;
                    }

                    long diff = Long.valueOf(json_data.getString("time")) - unix_time;

                    double rate_up = (json_data.getDouble("bandwidth_up") - bw_up) / diff;
                    double rate_down = (json_data.getDouble("bandwidth_down") - bw_down) / diff;

                    if (rate_up < 0.0)
                        rate_up = 0.0;
                    if (rate_down < 0.0)
                        rate_down = 0.0;

                    bw_graphview.addSample(bw_graph_up, unix_time, (float) rate_up);
                    bw_graphview.addSample(bw_graph_down, unix_time, (float) rate_down);

                    //                        Log.d(TAG, "time: " + diff +
                    //                            ", rate_up: " + rate_up + ", rate_down: " + rate_down);
                    bw_up = json_data.getDouble("bandwidth_up");
                    bw_down = json_data.getDouble("bandwidth_down");

                    loadavg_graphview.addSample(loadavg_graph_5min, unix_time,
                            (float) json_data.getDouble("loadavg_5min"));
                    loadavg_graphview.addSample(loadavg_graph_15min, unix_time,
                            (float) json_data.getDouble("loadavg_15min"));

                    mem_graphview.addSample(mem_graph_active, unix_time,
                            (float) json_data.getDouble("mem_active"));
                    mem_graphview.addSample(mem_graph_swap, unix_time,
                            (float) json_data.getDouble("mem_swap_used"));

                    unix_time = Long.valueOf(json_data.getString("time"));
                }
            } while (cursor.moveToNext());

            bw_graphview.update();
            loadavg_graphview.update();
            mem_graphview.update();
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    cursor.close();
}

From source file:com.flowzr.export.FlowzrIntegrationTest.java

public void test_push_category() throws Exception {

    if (dba.getAllCategories().getCount() == 2) { //only system categories
        Map<String, Category> categories = CategoryBuilder.createDefaultHierarchy(dba);
        FlowzrSyncEngine.fixCreatedEntities();
    }/*ww  w. j  a  va 2 s .c  o m*/

    FlowzrSyncEngine.pushUpdate("attributes", Attribute.class);
    FlowzrSyncEngine.pushUpdate("category", Category.class);

    JSONObject json = getJsonResponse(
            FlowzrSyncEngine.FLOWZR_API_URL + "admin_example.com/category/?last_sync_ts=0");
    JSONArray result = json.getJSONArray("category");
    Cursor cursor = dba.getCategories(false);
    //minus two system categories
    assertEquals(valueOf(cursor.getCount()), valueOf(result.length()));

    if (cursor.moveToFirst()) {
        do {
            // the view doesn't contains remote_key, the test is unoptimized
            Category expect = em.load(Category.class, cursor.getInt(cursor.getColumnIndex("_id")));
            boolean gotIt = false;
            for (int i = 0; i < result.length(); i++) {
                if (expect.remoteKey.equals(result.getJSONObject(i).getString("key"))) {

                    assertEquals(expect.getTitle(), result.getJSONObject(i).getString("name"));
                    if (expect.getParentId() > 0) {
                        assertEquals(em.load(Category.class, expect.getParentId()).remoteKey,
                                result.getJSONObject(i).getString("parentCategory"));
                    }
                    assertEquals(expect.type, result.getJSONObject(i).getInt("type"));
                    gotIt = true;
                }
            }
            assertTrue(expect.title, gotIt);

        } while (cursor.moveToNext());

    }
    cursor.close();

}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testUpdate() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    GroupAccess groupAccess = new GroupAccess(1, "fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds.");
    groupAccess.setLastTokenRequest(currentDate);
    groupAccess.setLastUpdateFromServer(currentDate);
    groupAccess.setSynchronize(true);// ww w .j  a  va2 s  .c  o m
    groupAccess.setInterrupted(true);

    assertTrue(mGroupAuthAccessDbController.update(groupAccess));

    Cursor cursor = db.query(GroupAccess.TABLE_NAME, GroupAccess.COLUMN.ALL_COLUMNS,
            GroupAccess.COLUMN.GROUP_ID + " = ? ", new String[] { String.valueOf(1) }, null, null, null);
    int count = cursor.getCount();
    if (count == 0)
        cursor.close();

    assertTrue(cursor.moveToFirst());
    int groupId = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.GROUP_ID));
    boolean synchronize = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.SYNCHRONIZE)) == 1;
    boolean interrupted = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.INTERRUPTED)) == 1;
    Date lastTokenRequestDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_TOKEN_REQUEST)),
            new ParsePosition(0));
    Date lastUpdateDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER)),
            new ParsePosition(0));
    String token = cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.TOKEN));
    cursor.close();

    assertEquals(1, groupId);
    assertEquals(true, synchronize);
    assertEquals(true, interrupted);
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastTokenRequestDate));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastUpdateDate));

    assertEquals("fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds.", token);

}

From source file:com.flowzr.export.FlowzrIntegrationTest.java

public void test_push_accounts() throws Exception {
    if (dba.em().getAllAccounts().getCount() < 1) {
        Currency c = createCurrency("CZK");
        com.flowzr.model.Account a = new com.flowzr.model.Account();
        a.title = "My Bank Account";
        a.type = AccountType.BANK.name();
        a.currency = c;//  w w w  .ja va 2  s  .  c  o m
        a.totalAmount = 23450;
        a.sortOrder = 50;
        a.cardIssuer = "card issuer";
        a.closingDay = 30;
        a.creationDate = 0;
        a.isActive = true;
        a.isIncludeIntoTotals = true;
        a.issuer = "issuer";
        a.limitAmount = 1000;
        a.note = "note";
        a.number = "6004300";
        a.paymentDay = 1;
        a.sortOrder = 1;
        a.id = -1;
        dba.em().saveAccount(a);
    }

    FlowzrSyncEngine.fixCreatedEntities();
    FlowzrSyncEngine.pushUpdate("currency", Currency.class);
    FlowzrSyncEngine.pushUpdate("account", com.flowzr.model.Account.class);

    JSONObject json = getJsonResponse(
            FlowzrSyncEngine.FLOWZR_API_URL + "admin_example.com/account/?last_sync_ts=0");
    JSONArray arr = json.getJSONArray("account");

    Cursor cursor = dba.em().getAllAccounts();

    assertEquals(valueOf(cursor.getCount()), valueOf(arr.length()));

    if (cursor.moveToFirst()) {
        do {
            //Log.i("flowzr", "account:" + cursor.getInt(0) + " " + cursor.getString(cursor.getColumnIndex("name")) + " " + cursor.getInt(cursor.getColumnIndex("remote_key")));
            // the view doesn't contains remote_key, the test is unoptimized
            com.flowzr.model.Account a = dba.em().getAccount(cursor.getInt(cursor.getColumnIndex("_id")));
            //em.load(Attribute.class, cursor.getInt(cursor.getColumnIndex("_id")));
            boolean gotIt = false;
            for (int i = 0; i < arr.length(); i++) {
                if (a.remoteKey.equals(arr.getJSONObject(i).getString("key"))) {
                    Log.i("flowzr", "got account " + a.title);
                    assertEquals(a.title, arr.getJSONObject(i).getString("name"));
                    assertEquals(a.type, arr.getJSONObject(i).getString("type"));
                    assertEquals(a.currency.name, arr.getJSONObject(i).getString("currency_name"));
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    if (a.cardIssuer != null) {
                        assertEquals(a.cardIssuer, arr.getJSONObject(i).getString("card_issuer"));
                    }
                    assertEquals(a.closingDay, arr.getJSONObject(i).getInt("closing_day"));
                    ;
                    assertFalse(a.isActive == arr.getJSONObject(i).getBoolean("hidden"));
                    assertEquals(a.isIncludeIntoTotals,
                            arr.getJSONObject(i).getBoolean("is_include_into_totals"));
                    if (a.issuer != null) {
                        assertEquals(a.issuer, arr.getJSONObject(i).getString("issuer"));
                    }
                    assertEquals(a.limitAmount, arr.getJSONObject(i).getInt("total_limit"));
                    if (a.note != null) {
                        assertEquals(a.note, arr.getJSONObject(i).getString("description"));
                    }
                    if (a.number != null) {
                        assertEquals(a.number, arr.getJSONObject(i).getString("code"));
                    }
                    assertEquals(a.paymentDay, arr.getJSONObject(i).getInt("payment_day"));
                    ;
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    gotIt = true;
                }
            }
            assertTrue(gotIt);
        } while (cursor.moveToNext());
    }
    cursor.close();
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private void mergeDbs() {
    Log.d(LOG_TAG, "update received - juggling dbs");
    // Get main database, attach temp db to it.
    SQLiteDatabase mainDb = dataService.getHelper().getWritableDatabase();
    mainDb.execSQL("attach database ? as ka_temp",
            new Object[] { dataService.getDatabasePath("ka_temp").getAbsolutePath() });

    mainDb.beginTransaction();/* ww w.  j  a  v  a  2 s  . c o  m*/
    try {

        // Maintain download status.
        String sql = "select max(download_status), dlm_id, youtube_id from video where download_status != ? group by youtube_id";
        Cursor c = mainDb.rawQuery(sql, new String[] { "" + Video.DL_STATUS_NOT_STARTED });
        Cursor c1;
        String[] videoIds = new String[c.getCount()];
        int i = 0;
        while (c.moveToNext()) {
            String youtube_id = c.getString(c.getColumnIndex("youtube_id"));
            String download_status = c.getString(c.getColumnIndex("max(download_status)"));
            long dlm_id = c.getLong(c.getColumnIndex("dlm_id"));
            videoIds[i++] = youtube_id;
            ContentValues v = new ContentValues();
            v.put("download_status", download_status);
            v.put("dlm_id", dlm_id);
            String[] idArg = new String[] { youtube_id };
            mainDb.update("ka_temp.video", v, "youtube_id = ?", idArg);

            // cursor over parent topics of this video
            sql = "select ka_temp.topic._id from ka_temp.topic, ka_temp.topicvideo, ka_temp.video where ka_temp.video.youtube_id=? and ka_temp.topicvideo.video_id=ka_temp.video.readable_id and ka_temp.topicvideo.topic_id=ka_temp.topic._id";
            c1 = mainDb.rawQuery(sql, idArg);
            Log.d(LOG_TAG, String.format("updating counts for %d topics", c1.getCount()));
            while (c1.moveToNext()) {
                String topicId = c1.getString(c1.getColumnIndex("_id"));
                DatabaseHelper.incrementDownloadedVideoCounts(mainDb, topicId, "ka_temp.topic");
            }
            c1.close();
        }
        c.close();

        mainDb.execSQL("delete from topic");
        mainDb.execSQL("insert into topic select * from ka_temp.topic");

        mainDb.execSQL("delete from topicvideo");
        mainDb.execSQL("insert into topicvideo select * from ka_temp.topicvideo");

        mainDb.execSQL("delete from video");
        mainDb.execSQL("insert into video select * from ka_temp.video");

        mainDb.setTransactionSuccessful();
    } finally {
        mainDb.endTransaction();
        mainDb.execSQL("detach database ka_temp");
    }

    Log.d(LOG_TAG, "finished juggling");
}

From source file:com.flowzr.export.FlowzrIntegrationTest.java

public void test_push_attributes() throws Exception {

    if (dba.getAllCategories().getCount() == 2) { //only system categories
        Map<String, Category> categories = CategoryBuilder.createDefaultHierarchy(dba);
        FlowzrSyncEngine.fixCreatedEntities();
    }/* w  ww  .  j a  va2 s. c  om*/

    FlowzrSyncEngine.pushUpdate("attributes", Attribute.class);

    JSONObject json = getJsonResponse(
            FlowzrSyncEngine.FLOWZR_API_URL + "admin_example.com/attributes/?last_sync_ts=0");
    JSONArray arr = json.getJSONArray("attributes");
    Cursor cursor = dba.getAllAttributes();
    //minus two system attributes ???
    assertEquals(valueOf(cursor.getCount()), valueOf(arr.length()));

    if (cursor.moveToFirst()) {
        do {
            Log.i("flowzr", "attr:" + cursor.getInt(0) + " " + cursor.getString(cursor.getColumnIndex("name"))
                    + " " + cursor.getInt(cursor.getColumnIndex("remote_key")));
            // the view doesn't contains remote_key, the test is unoptimized
            Attribute c = dba.getAttribute(cursor.getInt(cursor.getColumnIndex("_id")));
            //em.load(Attribute.class, cursor.getInt(cursor.getColumnIndex("_id")));
            boolean gotIt = false;
            for (int i = 0; i < arr.length(); i++) {
                if (c.remoteKey.equals(arr.getJSONObject(i).getString("key"))) {
                    Log.i("flowzr", "got attribute " + c.name);
                    assertEquals(c.name, arr.getJSONObject(i).getString("name"));
                    assertEquals(c.type, arr.getJSONObject(i).getInt("type"));
                    if (c.listValues != null) {
                        assertEquals(c.listValues, arr.getJSONObject(i).getString("list_values"));
                    }
                    if (c.defaultValue != null) {
                        assertEquals(c.defaultValue, arr.getJSONObject(i).getString("default_value"));
                    }
                    gotIt = true;
                }
            }
            //is the object find ?
            assertTrue(gotIt);
        } while (cursor.moveToNext());

    }
    cursor.close();
}

From source file:myblog.richard.vewe.launcher3.LauncherApplication.java

public boolean applistChanged() {
    Cursor cursor = getContentResolver().query(UsersContract.TableApplist.DIGA_URI,
            UsersContract.TableApplist.BASIC_COLUMNS, null, null, null);
    if (cursor == null || cursor.getCount() < 1) {
        if (mApplist.size() == 0)
            return false;
        else// ww  w. j  a va  2s  .  com
            return true;
    } else {
        if (mApplist.size() != cursor.getCount())
            return true;

        while (cursor.moveToNext()) {
            App app = new App(cursor);
            boolean match = false;
            for (App cmp : mApplist) {
                if (app.getPkgName().contentEquals(cmp.getPkgName())) //same package
                {
                    match = true;
                    if (app.getPkgType() != cmp.getPkgType()) {
                        return true;
                    }
                    break;
                }
            }
            if (match == false) {
                return true;
            }
        }
        cursor.close();
    }
    return false;
}

From source file:com.markupartist.sthlmtraveling.RouteDetailActivity.java

private boolean isStarredJourney(JourneyQuery journeyQuery) {
    String json;/*ww  w .  j a v a 2s  .  co  m*/
    try {
        json = mJourneyQuery.toJson(false).toString();
    } catch (JSONException e) {
        Log.e(TAG, "Failed to convert journey to a json document.");
        return false;
    }

    String[] projection = new String[] { Journeys.JOURNEY_DATA, };
    Uri uri = Journeys.CONTENT_URI;
    String selection = Journeys.STARRED + " = ? AND " + Journeys.JOURNEY_DATA + " = ?";
    String[] selectionArgs = new String[] { "1", json };
    Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, null);

    return cursor.getCount() > 0;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public boolean buscarDado(String dado) {
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;/*from  ww w .  ja  v  a2s .  c  om*/
    Cursor c = null;
    db = helper.getWritableDatabase();
    c = db.rawQuery("SELECT " + DBHelper.ID_INSCRITOS + " FROM " + DBHelper.INSCRITOS + " WHERE "
            + DBHelper.ID_INSCRITOS + " = '" + dado + "'", null);
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        Log.i("Script: ", "Busca encontrada! " + dado);
        c.close();
        return true;
    } else {
        Log.i("Script: ", "Busca no encontrada! " + dado);
        c.close();
        return false;
    }
}

From source file:de.fahrgemeinschaft.RideDetailsFragment.java

private void updateOptionsMenu() {
    Cursor cursor = getCursor();
    if (cursor != null && cursor.getCount() >= selected && edit != null && getActivity() != null) {
        cursor.moveToPosition(selected);
        if (isMyRide(cursor)) {
            edit.setVisible(true);//from   ww w . j a  v a 2s.co  m
            delete.setVisible(true);
            duplicate.setVisible(true);
            duplicate_retour.setVisible(true);
            toggle_active.setVisible(true);
            if (cursor.getInt(COLUMNS.ACTIVE) == 1) {
                toggle_active.setTitle(R.string.deactivate);
            } else {
                toggle_active.setTitle(R.string.activate);
            }
        } else {
            edit.setVisible(false);
            delete.setVisible(false);
            duplicate.setVisible(false);
            duplicate_retour.setVisible(false);
            toggle_active.setVisible(false);
        }
    }
}