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.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test that query for the next card in the schedule returns a valid result WITH a deck selector
 *//*from w  w  w .  ja v a 2s.  co  m*/
public void testQueryCardFromCertainDeck() {
    long deckToTest = mTestDeckIds[0];
    String deckSelector = "deckID=?";
    String deckArguments[] = { Long.toString(deckToTest) };
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();
    long selectedDeckBeforeTest = col.getDecks().selected();
    col.getDecks().select(1); //select Default deck

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, deckSelector, deckArguments, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());
    try {
        reviewInfoCursor.moveToFirst();
        int cardOrd = reviewInfoCursor
                .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
        long noteID = reviewInfoCursor
                .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));
        assertEquals("Check that the selected deck has not changed", 1, col.getDecks().selected());

        col.getDecks().select(deckToTest);
        Card nextCard = null;
        for (int i = 0; i < 10; i++) {//minimizing fails, when sched.reset() randomly chooses between multiple cards
            sched.reset();
            nextCard = sched.getCard();
            if (nextCard.note().getId() == noteID && nextCard.getOrd() == cardOrd)
                break;
        }
        assertNotNull("Check that there actually is a next scheduled card", nextCard);
        assertEquals("Check that received card and actual card have same note id", nextCard.note().getId(),
                noteID);
        assertEquals("Check that received card and actual card have same card ord", nextCard.getOrd(), cardOrd);
    } finally {
        reviewInfoCursor.close();
    }

    col.getDecks().select(selectedDeckBeforeTest);
}

From source file:com.kll.collect.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
 * an instance, it will be used to fill the {@link FormDef}.
 *///w w w  . j av a  2s.  c o  m
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);

    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    initializeJavaRosa();

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);

    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        Log.i("CSVMD5", csvmd5);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(oldmd5);
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5);
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (csvmd5 != null) {
        fc.setItemsetHash(csvmd5);
    }
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:org.tomahawk.libtomahawk.database.DatabaseHelper.java

/**
 * @return the count of all logged ops that should be delivered to the API
 *///  w ww .j  a  va2 s .com
public int getLoggedOpsCount() {
    String[] columns = new String[] { TomahawkSQLiteHelper.INFOSYSTEMOPLOG_COLUMN_ID };

    Cursor opLogCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_INFOSYSTEMOPLOG, columns, null, null, null,
            null, null);
    int count = opLogCursor.getCount();
    opLogCursor.close();
    return count;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test query to decks table//  w w  w. j  av a 2s.  c  o  m
 * @throws Exception
 */
public void testQueryAllDecks() throws Exception {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Decks decks = col.getDecks();

    Cursor decksCursor = getContext().getContentResolver().query(FlashCardsContract.Deck.CONTENT_ALL_URI,
            FlashCardsContract.Deck.DEFAULT_PROJECTION, null, null, null);

    assertNotNull(decksCursor);
    try {
        assertEquals("Check number of results", decks.count(), decksCursor.getCount());
        while (decksCursor.moveToNext()) {
            long deckID = decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID));
            String deckName = decksCursor
                    .getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME));

            JSONObject deck = decks.get(deckID);
            assertNotNull("Check that the deck we received actually exists", deck);
            assertEquals("Check that the received deck has the correct name", deck.getString("name"), deckName);
        }
    } finally {
        decksCursor.close();
    }
}

From source file:net.exclaimindustries.geohashdroid.services.WikiService.java

private ImageInfo readImageInfo(Uri uri, Location locationIfNoneSet) {
    // We're hoping this is something that MediaStore understands.  If not,
    // or if the image doesn't exist anyway, we're returning null, which is
    // interpreted by the intent handler to mean there's no image here, so
    // an error should be thrown.
    ImageInfo toReturn = null;//  w  w w. j ava  2 s  .co m

    if (uri != null) {
        Cursor cursor;
        cursor = getContentResolver().query(uri,
                new String[] { MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.LATITUDE,
                        MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DATE_TAKEN },
                null, null, null);

        if (cursor == null || cursor.getCount() < 1) {
            if (cursor != null)
                cursor.close();
            return null;
        }

        cursor.moveToFirst();

        toReturn = new ImageInfo();
        toReturn.uri = uri;
        toReturn.filename = cursor.getString(0);
        toReturn.timestamp = cursor.getLong(3);

        // These two could very well be null or empty.  Nothing wrong with
        // that.  But if they're good, make a Location out of them.
        String lat = cursor.getString(1);
        String lon = cursor.getString(2);

        Location toSet;
        try {
            double llat = Double.parseDouble(lat);
            double llon = Double.parseDouble(lon);
            toSet = new Location("");
            toSet.setLatitude(llat);
            toSet.setLongitude(llon);
        } catch (Exception ex) {
            // If we get an exception, we got it because of the number
            // parser.  Assume it's invalid and we're using the user's
            // current location, if that's even known (that might ALSO be
            // null, in which case we just don't have any clue where the
            // user is, which seems a bit counterintuitive to how
            // Geohashing is supposed to work).
            toSet = locationIfNoneSet;
        }

        // Now toss the location into the info.
        toReturn.location = toSet;

        cursor.close();
    }

    return toReturn;
}

From source file:net.smart_json_database.JSONDatabase.java

private void getHasManyRelationsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    HashMap<String, HasMany> hasManyRelations = new HashMap<String, HasMany>();
    String sql = "SELECT * FROM " + TABLE_REL_JSON_DATA_JSON_DATA + " WHERE from_id = ?";

    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();/* w ww .ja  v a  2  s  .com*/
        int col_from_id = c.getColumnIndex("to_id");
        int col_rel_name = c.getColumnIndex("rel_name");
        do {
            name = c.getString(col_rel_name);
            if (hasManyRelations.containsKey(name)) {
                hasManyRelations.get(name).put(c.getInt(col_from_id));
            } else {
                hasManyRelations.put(name, new HasMany(name));
                hasManyRelations.get(name).put(c.getInt(col_from_id));
            }
        } while (c.moveToNext());
    }
    c.close();
    entity.setHasManyRelations(hasManyRelations);
}

From source file:net.smart_json_database.JSONDatabase.java

private void getBelongsToRelationsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    HashMap<String, BelongsTo> belongsToRelations = new HashMap<String, BelongsTo>();
    String sql = "SELECT * FROM " + TABLE_REL_JSON_DATA_JSON_DATA + " WHERE to_id = ?";

    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();/*  w w  w  .jav  a  2s.c o  m*/
        int col_from_id = c.getColumnIndex("from_id");
        int col_rel_name = c.getColumnIndex("rel_name");
        do {
            name = c.getString(col_rel_name);
            if (belongsToRelations.containsKey(name)) {
                belongsToRelations.get(name).put(c.getInt(col_from_id));
            } else {
                belongsToRelations.put(name, new BelongsTo(name));
                belongsToRelations.get(name).put(c.getInt(col_from_id));
            }
        } while (c.moveToNext());
    }
    c.close();
    entity.setBelongsToRelations(belongsToRelations);

}

From source file:net.smart_json_database.JSONDatabase.java

public Collection<String> getPropertyKeys() {
    ArrayList<String> arrayList = new ArrayList<String>();
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT * FROM " + TABLE_Meta, new String[] {});

    if (c.getCount() > 0) {
        int key_col = c.getColumnIndex("key");
        c.moveToFirst();/*from w  w w  .  j a v a2s  .c o  m*/
        if (c != null) {
            if (c.isFirst()) {
                do {
                    arrayList.add(c.getString(key_col));
                } while (c.moveToNext());
            }
        }
    }
    c.close();

    return arrayList;
}

From source file:net.smart_json_database.JSONDatabase.java

private void getTagsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    ArrayList<String> names = new ArrayList<String>();
    String sql = "SELECT * FROM " + TABLE_REL_TAG_JSON_DATA + " WHERE to_id = ?";
    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();/*from   w  w  w.ja  va  2  s.  c  o m*/
        int col_from_id = c.getColumnIndex("from_id");
        do {
            name = invertedTags.get(new Integer(c.getInt(col_from_id)));
            if (name == null) {
                continue;
            }
            if (names.contains(name)) {
                continue;
            }
            names.add(name);
        } while (c.moveToNext());
    }
    c.close();
    if (names.size() > 0) {
        TagRelation relation = new TagRelation();
        relation.init(names);
        entity.setTags(relation);
    }
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

/**
 * Insert/Update the out-of-date sync status for an element (data or group) and return true if the sync adapter needs
 * to be triggered//  www . j  a  va2 s .  co m
 *
 * @param uriElement String of characters used to identify a name of a resource
 * @param idName     Unique name string
 * @param tableName  an element (data or group)
 * @param idElement  Unique element Identifier
 * @return true if the sync adapter needs to be triggered
 */
private boolean updateTrackSyncStatus(Uri uriElement, String idName, String tableName, String idElement) {

    boolean triggerSyncAdapter = true;

    ContentValues contentValues = new ContentValues();
    contentValues.put(idName, idElement);
    contentValues.put(CatalogContract.DataBaseSyncStatusGroup.ATT_STATUS, SyncStatus.OUTOFDATE.getValue());

    // Cursor to check if we need to trigger the sync adapter (data out-of-date)
    Cursor cursorCheckUpToDate = mDatabaseHelper.getReadableDatabase().query(tableName,
            new String[] { CatalogContract.DataBaseData.ATT_STATUS }, idName + "=?", new String[] { idElement },
            null, null, null);

    // Checking if we need to trigger the sync adapter
    if (cursorCheckUpToDate != null && cursorCheckUpToDate.getCount() > 0) {
        cursorCheckUpToDate.moveToFirst();

        // Sync status flag to out-of-date
        triggerSyncAdapter = (cursorCheckUpToDate.getInt(0) == SyncStatus.OUTOFDATE.getValue());

        cursorCheckUpToDate.close();
    }

    // Insert (or update) the row for the sync status out-to-date:
    // Case 1: we need to trigger the sync adapter
    // Case 2: the value is up-to-date, we invalidate the sync status for the next calls to the provider
    insert(Uri.withAppendedPath(uriElement, idElement), contentValues);

    return triggerSyncAdapter;
}