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.jaspersoft.android.jaspermobile.activities.profile.ServerProfileActivity.java

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    switch (cursorLoader.getId()) {
    case LOAD_PROFILE:
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();//from   ww w .j  av a  2 s  .co m
            updateProfileFields(cursor);
        }
        break;
    case QUERY_UNIQUENESS:
        checkUniqueConstraintFulfilled(cursor);
        break;
    }
}

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

/**
 * Gets a task (if exists) from the "remote" table of the database.
 *
 * @param id ID of task to search for// w w w .  ja  va 2 s .  c  om
 * @return Task found, if nothing found returns null.
 * @throws JSONException 
 */
public Task getRemoteTask(String id) {
    try {
        Cursor c = db.rawQuery(
                "SELECT * FROM " + StringRes.REMOTE_TASK_TABLE_NAME + " WHERE " + StringRes.COL_ID + "=?",
                new String[] { id, });
        c.moveToFirst();
        if (c == null || c.getCount() == 0) {
            return null;
        } else {
            String taskContent = c.getString(c.getColumnIndex(StringRes.COL_CONTENT));
            JSONObject jsonTask = toJsonTask(taskContent);
            return toTask(jsonTask);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:mobisocial.musubi.util.UriImage.java

private void initFromContentUri(Context context, Uri uri) {
    Cursor c = context.getContentResolver().query(uri, null, null, null, null);

    if (c == null) {
        throw new IllegalArgumentException("Query on " + uri + " returns null result.");
    }//from  w  w  w  .ja v a  2  s.c  o  m

    try {
        if ((c.getCount() != 1) || !c.moveToFirst()) {
            throw new IllegalArgumentException("Query on " + uri + " returns 0 or multiple rows.");
        }

        String filePath = c.getString(c.getColumnIndexOrThrow(Images.Media.DATA));
        mContentType = c.getString(c.getColumnIndexOrThrow(Images.Media.MIME_TYPE));
        mPath = filePath;
    } finally {
        c.close();
    }
}

From source file:mai.whack.StickyNotesActivity.java

private void onDataWrite(Intent intent) {
    byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
    Cursor mCur = this.managedQuery(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, "DATE");
    // mCur.moveToFirst();
    if (mCur.moveToLast() && mCur.getCount() > 0) {
        String url = mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
        mHttpPostThread = new HttpPostThread(toHex(tagId), "tabs", url);
        mHttpPostThread.start();//from   ww w  .  j a  v a2s  .c  o  m
    }
}

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

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

    Cursor cursor = getContext().getContentResolver().query(TestContract.CONTENT_URI_BOOKS_AUTHORS2, //uri
            BOOKS_AUTHORS_PROJECTION, //projection
            TestContract.BookAuthor.AUTHOR_ID + "=?", //selection
            new String[] { "sashab" }, //selectionArgs
            TestContract.Book.TITLE + " ASC" //sort order
    );/*from w w w.jav  a  2  s . c o m*/

    assertTrue(cursor != null);
    assertTrue(cursor.getCount() == 2);
}

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

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

    Cursor cursor = getContext().getContentResolver().query(TestContract.CONTENT_URI_BOOKS_AUTHORS3, //uri
            BOOKS_AUTHORS_PROJECTION, //projection
            TestContract.BookAuthor.AUTHOR_ID + "=?", //selection
            new String[] { "sashab" }, //selectionArgs
            TestContract.Book.TITLE + " ASC" //sort order
    );/* ww w .j a va 2 s.  c  o  m*/

    assertTrue(cursor != null);
    assertTrue(cursor.getCount() == 2);
}

From source file:ru.orangesoftware.financisto.activity.FlowzrIntegrationTest.java

public void test_push_accounts() throws Exception {
    if (dba.em().getAllAccounts().getCount() < 1) {
        Currency c = createCurrency("CZK");
        ru.orangesoftware.financisto.model.Account a = new ru.orangesoftware.financisto.model.Account();
        a.title = "My Bank Account";
        a.type = AccountType.BANK.name();
        a.currency = c;//  ww  w  . ja  va2s .  co  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", ru.orangesoftware.financisto.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
            ru.orangesoftware.financisto.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.winsuk.pebbletype.WatchCommunication.java

private void sendThreadList(Context context) {
    Cursor msgCursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null,
            null);//from  w  w  w.  j  a  v a  2s.c  om
    Activity act = new Activity();
    act.startManagingCursor(msgCursor);
    ArrayList<SMSThread> threads = new ArrayList<SMSThread>();

    if (msgCursor.moveToFirst()) {
        for (int i = 0; i < msgCursor.getCount(); i++) {
            int thread_id = msgCursor.getInt(msgCursor.getColumnIndexOrThrow("thread_id"));
            SMSThread th = null;
            for (int t = 0; t < threads.size(); t++) {
                SMSThread existingTh = threads.get(t);
                if (existingTh.thread_id == thread_id) {
                    th = existingTh;
                }
            }

            if (th == null) {
                String address = msgCursor.getString(msgCursor.getColumnIndexOrThrow("address")).toString();
                String name = "";

                Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
                Cursor contactCursor = context.getContentResolver().query(uri,
                        new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
                if (contactCursor.moveToFirst()) {
                    name = contactCursor.getString(contactCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                    contactCursor.close();
                }

                th = new SMSThread();
                th.thread_id = thread_id;
                th.address = address;
                th.name = name;
                //th.messages = new ArrayList<String>();
                threads.add(th);
            }

            /* TODO: this line is causing crashes on select few devices
            String body = msgCursor.getString(msgCursor.getColumnIndexOrThrow("body")).toString();
            if (th.messages.size() < 5) {
               th.messages.add(body);
            }
            */

            msgCursor.moveToNext();
        }
    }
    msgCursor.close();

    int limit = (threads.size() <= THREAD_LIMIT ? threads.size() : THREAD_LIMIT);
    String output = "";

    if (limit > 0) {
        // Calculate how many characters names can take up
        int availibleCharacters = 120;
        for (int i = 0; i < limit; i++) {
            availibleCharacters -= threads.get(i).address.length();
            availibleCharacters -= 2; //for ; and \n
        }
        int maxNameLength = availibleCharacters / limit - 3;

        for (int i = 0; i < limit; i++) {
            SMSThread thread = threads.get(i);

            String name = "";
            if (thread.name.length() < maxNameLength) {
                name = thread.name;
            } else {
                name = thread.name.substring(0, maxNameLength - 1);
                name += "";
            }

            output = output + thread.address + ";" + name + "\n";

            /* List messages
            for (int ii = 0; ii < thread.messages.size(); ii++) {
               output = output + thread.messages.get(ii) + "\n";
            }*/
        }
    }
    PebbleDictionary data = new PebbleDictionary();
    data.addString(KEY_THREAD_LIST, output);
    PebbleKit.sendDataToPebble(context, PEBBLE_APP_UUID, data);
}

From source file:org.noorganization.instalistsynch.controller.synch.impl.RecipeSynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000");
    boolean isLocal = false;
    GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup();
    if (groupAuth != null) {
        isLocal = groupAuth.getGroupId() == _groupId;
    }/*  w  w  w.java  2s.c o  m*/
    Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType);
    if (logCursor.getCount() == 0) {
        logCursor.close();
        return;
    }

    try {
        while (logCursor.moveToNext()) {
            // fetch the action type
            int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(actionId);

            List<ModelMapping> modelMappingList = mRecipeMappingController.get(
                    ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID
                            + " LIKE ?",
                    new String[] { String.valueOf(_groupId),
                            logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) });
            ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0);

            switch (actionType) {
            case INSERT:
                // skip insertion because this should be decided by the user if the non local groups should have access to the category
                // and also skip if a mapping for this case already exists!
                if (!isLocal || modelMapping != null) {
                    continue;
                }

                String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
                Date clientDate = ISO8601Utils.parse(
                        logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid,
                        new Date(Constants.INITIAL_DATE), clientDate, false);
                mRecipeMappingController.insert(modelMapping);
                break;
            case UPDATE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mRecipeMappingController.update(modelMapping);
                break;
            case DELETE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                modelMapping.setDeleted(true);
                timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mRecipeMappingController.update(modelMapping);
                break;
            default:
            }

        }
    } catch (Exception e) {
        logCursor.close();
    }
}

From source file:de.fahrgemeinschaft.RideDetailsFragment.java

@Override
public void onClick(View v) {
    Cursor c = getCursor();
    if (c.getCount() > 0) {
        if (getCursor().getCount() <= selected)
            selected = c.getCount() - 1;
        c.moveToPosition(selected);//ww w  .j  av a  2  s  .c o m
        Util.openContactOptionsChooserDialog(getActivity(), getCursor());
    }
}