List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:com.hichinaschool.flashcards.libanki.Sched.java
public void sortCards(long[] cids, int start, int step, boolean shuffle, boolean shift) { String scids = Utils.ids2str(cids); long now = Utils.intNow(); ArrayList<Long> nids = new ArrayList<Long>(); for (long id : cids) { long nid = mCol.getDb().queryLongScalar("SELECT nid FROM cards WHERE id = " + id); if (!nids.contains(nid)) { nids.add(nid);/* w ww . java 2 s . c o m*/ } } if (nids.size() == 0) { // no new cards return; } // determine nid ordering HashMap<Long, Long> due = new HashMap<Long, Long>(); if (shuffle) { Collections.shuffle(nids); } for (int c = 0; c < nids.size(); c++) { due.put(nids.get(c), (long) (start + c * step)); } int high = start + step * (nids.size() - 1); // shift? if (shift) { int low = mCol.getDb().queryScalar( "SELECT min(due) FROM cards WHERE due >= " + start + " AND type = 0 AND id NOT IN " + scids, false); if (low != 0) { int shiftby = high - low + 1; mCol.getDb().execute("UPDATE cards SET mod = " + now + ", usn = " + mCol.usn() + ", due = due + " + shiftby + " WHERE id NOT IN " + scids + " AND due >= " + low + " AND queue = 0"); } } // reorder cards ArrayList<Object[]> d = new ArrayList<Object[]>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery("SELECT id, nid FROM cards WHERE type = 0 AND id IN " + scids, null); while (cur.moveToNext()) { long nid = cur.getLong(1); d.add(new Object[] { due.get(nid), now, mCol.usn(), cur.getLong(0) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } mCol.getDb().executeMany("UPDATE cards SET due = ?, mod = ?, usn = ? WHERE id = ?", d); }
From source file:com.ichi2.libanki.Sched.java
/** estimates remaining time for learning (based on last seven days) */ public int eta(int[] counts, boolean reload) { double revYesRate; double revTime; double lrnYesRate; double lrnTime; if (reload || mEtaCache[0] == -1) { Cursor cur = null; try {//w w w. j ava2 s . c o m cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease > 1 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type = 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } revYesRate = cur.getDouble(0); revTime = cur.getDouble(1); if (!cur.isClosed()) { cur.close(); } cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease = 3 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type != 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } lrnYesRate = cur.getDouble(0); lrnTime = cur.getDouble(1); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } mEtaCache[0] = revYesRate; mEtaCache[1] = revTime; mEtaCache[2] = lrnYesRate; mEtaCache[3] = lrnTime; } else { revYesRate = mEtaCache[0]; revTime = mEtaCache[1]; lrnYesRate = mEtaCache[2]; lrnTime = mEtaCache[3]; } // rev cards double eta = revTime * counts[2]; // lrn cards double factor = Math.min(1 / (1 - lrnYesRate), 10); double lrnAnswers = (counts[0] + counts[1] + counts[2] * (1 - revYesRate)) * factor; eta += lrnAnswers * lrnTime; return (int) (eta / 60000); }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public boolean DoStatusCheck() { String sts_sel;/*from w w w . j a va 2 s.c om*/ Cursor cur_sc; String sort; Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT; String[] projection = { GliderLogTables.F_STARTED, GliderLogTables.F_LANDED, GliderLogTables.F_DEL, GliderLogTables.F_HID }; sts_sel = "(" + GliderLogTables.F_STARTED + " IS '') AND (" + GliderLogTables.F_SENT + "=0) AND (" + GliderLogTables.F_HID + ">0)"; sort = GliderLogTables.F_SENT + " ASC, " + GliderLogTables.F_STARTED + " DESC"; cur_sc = getContentResolver().query(uri, projection, sts_sel, null, sort); if (cur_sc != null) { try { intSum[0] = cur_sc.getCount(); } finally { if (!cur_sc.isClosed()) { cur_sc.close(); } } } sts_sel = "(" + GliderLogTables.F_LANDED + " IS '') AND (" + GliderLogTables.F_SENT + "=0) AND (" + GliderLogTables.F_HID + ">0)"; sort = GliderLogTables.F_SENT + " ASC, " + GliderLogTables.F_STARTED + " DESC"; cur_sc = getContentResolver().query(uri, projection, sts_sel, null, sort); if (cur_sc != null) { try { intSum[1] = cur_sc.getCount(); } finally { if (!cur_sc.isClosed()) { cur_sc.close(); } } } sts_sel = "(" + GliderLogTables.F_DEL + "=1) AND (" + GliderLogTables.F_SENT + "=0) AND (" + GliderLogTables.F_HID + ">0)"; sort = GliderLogTables.F_SENT + " ASC, " + GliderLogTables.F_STARTED + " DESC"; cur_sc = getContentResolver().query(uri, projection, sts_sel, null, sort); if (cur_sc != null) { try { intSum[2] = cur_sc.getCount(); } finally { if (!cur_sc.isClosed()) { cur_sc.close(); } } } // if any of these check result in value not zero we have issue's return ((intSum[0] + intSum[1] + intSum[2]) == 0) ? true : false; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return all the tableIds in the database. * //from ww w . j a va 2s . c om * @param db * @return an ArrayList<String> of tableIds */ public ArrayList<String> getAllTableIds(SQLiteDatabase db) { ArrayList<String> tableIds = new ArrayList<String>(); Cursor c = null; try { c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, new String[] { TableDefinitionsColumns.TABLE_ID }, null, null, null, null, TableDefinitionsColumns.TABLE_ID + " ASC"); if (c.moveToFirst()) { int idxId = c.getColumnIndex(TableDefinitionsColumns.TABLE_ID); do { String tableId = c.getString(idxId); if (tableId == null || tableId.length() == 0) { c.close(); throw new IllegalStateException("getAllTableIds: Unexpected tableId found!"); } tableIds.add(tableId); } while (c.moveToNext()); } } finally { if (c != null && !c.isClosed()) { c.close(); } } return tableIds; }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private boolean _fillRev() { if (!mRevQueue.isEmpty()) { return true; }/* w w w . j a v a 2 s .c o m*/ if (mRevCount == 0) { return false; } while (mRevDids.size() > 0) { long did = mRevDids.getFirst(); int lim = Math.min(mQueueLimit, _deckRevLimit(did)); Cursor cur = null; if (lim != 0) { mRevQueue.clear(); // fill the queue with the current did try { cur = mCol.getDb().getDatabase().rawQuery("SELECT id FROM cards WHERE did = " + did + " AND queue = 2 AND due <= " + mToday + " LIMIT " + lim, null); while (cur.moveToNext()) { mRevQueue.add(cur.getLong(0)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mRevQueue.isEmpty()) { // ordering try { if (mCol.getDecks().get(did).getInt("dyn") != 0) { // dynamic decks need due order preserved // Note: libanki reverses mRevQueue and returns the last element in _getRevCard(). // AnkiDroid differs by leaving the queue intact and returning the *first* element // in _getRevCard(). } else { Random r = new Random(); r.setSeed(mToday); Collections.shuffle(mRevQueue, r); } } catch (JSONException e) { throw new RuntimeException(e); } // is the current did empty? if (mRevQueue.size() < lim) { mRevDids.remove(); } return true; } } // nothing left in the deck; move to next mRevDids.remove(); } if (mRevCount != 0) { // if we didn't get a card but the count is non-zero, // we need to check again for any cards that were // removed from the queue but not buried _resetRev(); return _fillRev(); } return false; }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private boolean _fillNew() { if (mNewQueue.size() > 0) { return true; }// ww w . j av a 2 s . co m if (mNewCount == 0) { return false; } while (!mNewDids.isEmpty()) { long did = mNewDids.getFirst(); int lim = Math.min(mQueueLimit, _deckNewLimit(did)); Cursor cur = null; if (lim != 0) { mNewQueue.clear(); try { // fill the queue with the current did cur = mCol.getDb().getDatabase().rawQuery( "SELECT id FROM cards WHERE did = " + did + " AND queue = 0 order by due LIMIT " + lim, null); while (cur.moveToNext()) { mNewQueue.add(cur.getLong(0)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mNewQueue.isEmpty()) { // Note: libanki reverses mNewQueue and returns the last element in _getNewCard(). // AnkiDroid differs by leaving the queue intact and returning the *first* element // in _getNewCard(). return true; } } // nothing left in the deck; move to next mNewDids.remove(); } if (mNewCount != 0) { // if we didn't get a card but the count is non-zero, // we need to check again for any cards that were // removed from the queue but not buried _resetNew(); return _fillNew(); } return false; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the health of a data table. The health can be one of * <ul>/*from ww w. ja va 2 s .c om*/ * <li>TABLE_HEALTH_IS_CLEAN = 0</li> * <li>TABLE_HEALTH_HAS_CONFLICTS = 1</li> * <li>TABLE_HEALTH_HAS_CHECKPOINTS = 2</li> * <li>TABLE_HEALTH_HAS_CHECKPOINTS_AND_CONFLICTS = 3</li> * <ul> * * @param db * @param tableId * @return */ public int getTableHealth(SQLiteDatabase db, String tableId) { StringBuilder b = new StringBuilder(); b.append("SELECT SUM(case when _savepoint_type is null then 1 else 0 end) as checkpoints,") .append("SUM(case when _conflict_type is not null then 1 else 0 end) as conflicts from \"") .append(tableId).append("\""); Cursor c = null; try { c = db.rawQuery(b.toString(), null); int idxCheckpoints = c.getColumnIndex("checkpoints"); int idxConflicts = c.getColumnIndex("conflicts"); c.moveToFirst(); Integer checkpoints = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, idxCheckpoints); Integer conflicts = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, idxConflicts); c.close(); int outcome = TABLE_HEALTH_IS_CLEAN; if (checkpoints != null && checkpoints != 0) { outcome += TABLE_HEALTH_HAS_CHECKPOINTS; } if (conflicts != null && conflicts != 0) { outcome += TABLE_HEALTH_HAS_CONFLICTS; } return outcome; } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java
private JSONGraphData loadBooleanPlot() { Date startDateToUse = getStartDate(); DateDisplayTypes displayType = this.getDisplayType(startDateToUse, mEndDate); String selectionArg = getSelectionString(displayType); StringBuilder rawQuery = new StringBuilder(); String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName(); rawQuery.append("select time, " + fieldcol + ", count(*) from "); rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix()); rawQuery.append(" join rapidandroid_message on ("); rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix()); rawQuery.append(".message_id = rapidandroid_message._id"); rawQuery.append(") "); if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) { rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse) + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' "); }//from w w w . j a v a2 s.co m rawQuery.append(" group by ").append(selectionArg).append(", " + fieldcol); rawQuery.append(" order by ").append("time").append(" ASC"); SQLiteDatabase db = rawDB.getReadableDatabase(); // the string value is column 0 // the magnitude is column 1 Log.d("query", rawQuery.toString()); Cursor cr = db.rawQuery(rawQuery.toString(), null); // TODO Auto-generated method stub int barCount = cr.getCount(); Date[] allDates = new Date[barCount]; if (barCount == 0) { db.close(); cr.close(); } else { List<Date> xValsTrue = new ArrayList<Date>(); // Date[] xValsTrue = new Date[barCount]; List<Integer> yValsTrue = new ArrayList<Integer>(); List<Date> xValsFalse = new ArrayList<Date>(); // Date[] xValsTrue = new Date[barCount]; List<Integer> yValsFalse = new ArrayList<Integer>(); cr.moveToFirst(); int i = 0; do { String trueFalse = cr.getString(1); // int trueFalse2 = cr.getInt(fieldcol); // String trueFalseStr = cr.getString(1); Date thisDate = getDate(displayType, cr.getString(0)); Log.d("FormDataBroker: ", cr.getString(0) + ", " + trueFalse + " , " + cr.getInt(2)); if (trueFalse.equals("true")) { xValsFalse.add(thisDate); yValsFalse.add(new Integer(cr.getInt(2))); } else { xValsTrue.add(thisDate); yValsTrue.add(new Integer(cr.getInt(2))); } allDates[i] = thisDate; i++; } while (cr.moveToNext()); try { // String legend = this.getLegendString(displayType); int[] yVals = getIntsFromList(yValsTrue); JSONArray trueArray = getJSONArrayForValues(displayType, xValsTrue.toArray(new Date[0]), yVals); yVals = getIntsFromList(yValsFalse); JSONArray falseArray = getJSONArrayForValues(displayType, xValsFalse.toArray(new Date[0]), yVals); JSONArray finalValues = new JSONArray(); JSONObject trueElem = new JSONObject(); trueElem.put("data", trueArray); trueElem.put("label", "Yes"); trueElem.put("lines", getShowTrue()); finalValues.put(trueElem); JSONObject falseElem = new JSONObject(); falseElem.put("data", falseArray); falseElem.put("label", "No"); falseElem.put("lines", getShowTrue()); finalValues.put(falseElem); return new JSONGraphData(finalValues, loadOptionsForDateGraph(allDates, true, displayType)); } catch (Exception ex) { } finally { if (!cr.isClosed()) { cr.close(); } if (db.isOpen()) { db.close(); } } } // either there was no data or something bad happened return new JSONGraphData(getEmptyData(), new JSONObject()); }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private boolean _fillLrn() { if (mLrnCount == 0) { return false; }// w ww . java 2 s. com if (!mLrnQueue.isEmpty()) { return true; } Cursor cur = null; mLrnQueue.clear(); try { cur = mCol.getDb().getDatabase().rawQuery("SELECT due, id FROM cards WHERE did IN " + _deckLimit() + " AND queue = 1 AND due < " + mDayCutoff + " LIMIT " + mReportLimit, null); while (cur.moveToNext()) { mLrnQueue.add(new long[] { cur.getLong(0), cur.getLong(1) }); } // as it arrives sorted by did first, we need to sort it Collections.sort(mLrnQueue, new DueComparator()); return !mLrnQueue.isEmpty(); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } }
From source file:de.ub0r.android.websms.WebSMS.java
/** * Load data from Conversation./*from www .ja v a 2 s .c o m*/ * * @param threadId ThreadId */ private void parseThreadId(final String threadId) { Log.d(TAG, "thradId: " + threadId); final Uri uri = Uri.parse("content://mms-sms/conversations/" + threadId); final String[] proj = new String[] { "thread_id", "address" }; Cursor cursor = null; try { try { cursor = this.getContentResolver().query(uri, proj, null, null, null); } catch (SQLException e) { Log.e(TAG, null, e); proj[0] = "_id"; proj[1] = "recipient_address"; cursor = this.getContentResolver().query(uri, proj, null, null, null); } if (cursor != null && cursor.moveToFirst()) { String a; do { a = cursor.getString(1); } while (a == null && cursor.moveToNext()); Log.d(TAG, "found address: " + a); this.parseSchemeSpecificPart(a); } } catch (IllegalStateException e) { Log.e(TAG, "error parsing ThreadId: " + threadId, e); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } }