List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Verifies that the tableId exists in the database. * * @param db/*from www. j a v a 2s . c o m*/ * @param tableId * @return true if table is listed in table definitions. */ public boolean hasTableId(SQLiteDatabase db, String tableId) { Cursor c = null; try { //@formatter:off c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, null, TableDefinitionsColumns.TABLE_ID + "=?", new String[] { tableId }, null, null, null); //@formatter:on if (c.moveToFirst()) { // we know about the table... // tableId is the database table name... return true; } } finally { if (c != null && !c.isClosed()) { c.close(); } } return false; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get remote files for given article/*from w w w. j ava 2 s. c o m*/ * * @param articleId article, which remote files should be found * @return collection of remote file objects from DB or {@code null} */ public Collection<RemoteFile> getRemoteFiles(int articleId) { if (!isDBAvailable()) return null; ArrayList<RemoteFile> rfs = null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { // @formatter:off c = db.rawQuery(" SELECT r.*" + " FROM " + TABLE_REMOTEFILES + " r," + TABLE_REMOTEFILE2ARTICLE + " m, " + TABLE_ARTICLES + " a" + " WHERE m.remotefileId=r.id" + " AND m.articleId=a._id" + " AND a._id=?", new String[] { String.valueOf(articleId) }); // @formatter:on rfs = new ArrayList<>(c.getCount()); while (c.moveToNext()) { rfs.add(handleRemoteFileCursor(c)); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return rfs; }
From source file:com.ichi2.libanki.Collection.java
/** Fix possible problems and rebuild caches. */ public long fixIntegrity() { File file = new File(mPath); ArrayList<String> problems = new ArrayList<String>(); long oldSize = file.length(); try {//from www . ja v a2s. c o m mDb.getDatabase().beginTransaction(); try { save(); if (!mDb.queryString("PRAGMA integrity_check").equals("ok")) { return -1; } // note types with a missing model ArrayList<Long> ids = mDb.queryColumn(Long.class, "SELECT id FROM notes WHERE mid NOT IN " + Utils.ids2str(mModels.ids()), 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " note(s) with missing note type."); _remNotes(Utils.arrayList2array(ids)); } // for each model for (JSONObject m : mModels.all()) { // cards with invalid ordinal if (m.getInt("type") == Consts.MODEL_STD) { ArrayList<Integer> ords = new ArrayList<Integer>(); JSONArray tmpls = m.getJSONArray("tmpls"); for (int t = 0; t < tmpls.length(); t++) { ords.add(tmpls.getJSONObject(t).getInt("ord")); } ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE ord NOT IN " + Utils.ids2str(ords) + " AND nid IN ( " + "SELECT id FROM notes WHERE mid = " + m.getLong("id") + ")", 0); if (ids.size() > 0) { problems.add("Deleted " + ids.size() + " card(s) with missing template."); remCards(Utils.arrayList2array(ids)); } } // notes with invalid field counts ids = new ArrayList<Long>(); Cursor cur = null; try { cur = mDb.getDatabase() .rawQuery("select id, flds from notes where mid = " + m.getLong("id"), null); while (cur.moveToNext()) { String flds = cur.getString(1); long id = cur.getLong(0); int fldsCount = 0; for (int i = 0; i < flds.length(); i++) { if (flds.charAt(i) == 0x1f) { fldsCount++; } } if (fldsCount + 1 != m.getJSONArray("flds").length()) { ids.add(id); } } if (ids.size() > 0) { problems.add("Deleted " + ids.size() + " note(s) with wrong field count."); _remNotes(Utils.arrayList2array(ids)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } } // delete any notes with missing cards ids = mDb.queryColumn(Long.class, "SELECT id FROM notes WHERE id NOT IN (SELECT DISTINCT nid FROM cards)", 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " note(s) with missing no cards."); _remNotes(Utils.arrayList2array(ids)); } // cards with missing notes ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE nid NOT IN (SELECT id FROM notes)", 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " card(s) with missing note."); remCards(Utils.arrayList2array(ids)); } // cards with odue set when it shouldn't be ids = mDb.queryColumn(Long.class, "select id from cards where odue > 0 and (type=1 or queue=2) and not odid", 0); if (ids.size() != 0) { problems.add("Fixed " + ids.size() + " card(s) with invalid properties."); mDb.execute("update cards set odue=0 where id in " + Utils.ids2str(ids)); } // cards with odid set when not in a dyn deck ArrayList<Long> dids = new ArrayList<Long>(); for (long id : mDecks.allIds()) { if (!mDecks.isDyn(id)) { dids.add(id); } } ids = mDb.queryColumn(Long.class, "select id from cards where odid > 0 and did in " + Utils.ids2str(dids), 0); if (ids.size() != 0) { problems.add("Fixed " + ids.size() + " card(s) with invalid properties."); mDb.execute("update cards set odid=0, odue=0 where id in " + Utils.ids2str(ids)); } // tags mTags.registerNotes(); // field cache for (JSONObject m : mModels.all()) { updateFieldCache(Utils.arrayList2array(mModels.nids(m))); } // new cards can't have a due position > 32 bits mDb.execute("UPDATE cards SET due = 1000000, mod = " + Utils.intNow() + ", usn = " + usn() + " WHERE due > 1000000 AND queue = 0"); // new card position mConf.put("nextPos", mDb.queryScalar("SELECT max(due) + 1 FROM cards WHERE type = 0")); // reviews should have a reasonable due ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE queue = 2 AND due > 10000", 0); if (ids.size() > 0) { problems.add("Reviews had incorrect due date."); mDb.execute("UPDATE cards SET due = 0, mod = " + Utils.intNow() + ", usn = " + usn() + " WHERE id IN " + Utils.ids2str(Utils.arrayList2array(ids))); } mDb.getDatabase().setTransactionSuccessful(); // DB must have indices. Older versions of AnkiDroid didn't create them for new collections. int ixs = mDb.queryScalar("select count(name) from sqlite_master where type = 'index'"); if (ixs < 7) { problems.add("Indices were missing."); Storage.addIndices(mDb); } } catch (JSONException e) { throw new RuntimeException(e); } finally { mDb.getDatabase().endTransaction(); } } catch (RuntimeException e) { Timber.e(e, "doInBackgroundCheckDatabase - RuntimeException on marking card"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundCheckDatabase"); return -1; } // and finally, optimize optimize(); file = new File(mPath); long newSize = file.length(); // if any problems were found, force a full sync if (problems.size() > 0) { modSchemaNoCheck(); } // TODO: report problems return (long) ((oldSize - newSize) / 1024); }
From source file:com.ichi2.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);/*from ww w. j a v a 2 s . com*/ } } 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); 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:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * //w w w. j a v a 2 s .co m * @param db * @param appName * @param tableId * @param rowId * @return the sync state of the row (see {@link SyncState}), or null if the * row does not exist. */ public SyncState getSyncState(SQLiteDatabase db, String appName, String tableId, String rowId) { Cursor c = null; try { c = db.query(tableId, new String[] { DataTableColumns.SYNC_STATE }, DataTableColumns.ID + " = ?", new String[] { rowId }, null, null, null); if (c.moveToFirst()) { int syncStateIndex = c.getColumnIndex(DataTableColumns.SYNC_STATE); if (!c.isNull(syncStateIndex)) { String val = getIndexAsString(c, syncStateIndex); return SyncState.valueOf(val); } } return null; } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java
@Override public FrameworkFormPathInfo getFrameworkFormPathInfo() { // Find the formPath for the default form with the most recent // version... Cursor c = null; String formPath = null;/* w ww . j a v a 2 s . com*/ Long lastModified = null; try { // // the default form is named 'default' ... String selection = FormsColumns.FORM_ID + "=?"; String[] selectionArgs = { FormsColumns.COMMON_BASE_FORM_ID }; // use the most recently created of the matches // (in case DB corrupted) String orderBy = FormsColumns.FORM_VERSION + " DESC"; c = getContentResolver().query(Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), null, selection, selectionArgs, orderBy); if (c != null && c.getCount() > 0) { // we found a match... c.moveToFirst(); formPath = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_PATH)); lastModified = ODKDatabaseUtils.get().getIndexAsType(c, Long.class, c.getColumnIndex(FormsColumns.DATE)); } } finally { if (c != null && !c.isClosed()) { c.close(); } } if (formPath == null) { return null; } else { return new FrameworkFormPathInfo(formPath, lastModified); } }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public String getTableFlightProgress() { String tmp_a, tmp_b;/*from ww w . j a v a 2s . com*/ String selection; Cursor cur_fp; String sort; Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT; String[] projection = { GliderLogTables.F_ID }; selection = "(" + GliderLogTables.F_STARTED + " IS NOT '' )"; sort = GliderLogTables.F_SENT + " ASC, " + GliderLogTables.F_STARTED + " DESC"; cur_fp = getContentResolver().query(uri, projection, selection, null, sort); if (cur_fp != null) { try { tmp_a = String.valueOf(cur_fp.getCount()); } finally { if (!cur_fp.isClosed()) { cur_fp.close(); } } } else { tmp_a = "0"; } selection = "(" + GliderLogTables.F_STARTED + " IS NOT '' AND " + GliderLogTables.F_HID + " > 0)"; sort = GliderLogTables.F_SENT + " ASC, " + GliderLogTables.F_STARTED + " DESC"; cur_fp = getContentResolver().query(uri, projection, selection, null, sort); if (cur_fp != null) { try { tmp_b = String.valueOf(cur_fp.getCount()); } finally { if (!cur_fp.isClosed()) { cur_fp.close(); } } } else { tmp_b = "0"; } return tmp_a + "/" + tmp_b; }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public void addItemSpinner_2() { Uri uri = FlightsContentProvider.CONTENT_URI_GLIDER; String[] projection = { GliderLogTables.G_REGISTRATION }; Cursor cur_sp = getContentResolver().query(uri, projection, null, null, GliderLogTables.G_REGISTRATION + " ASC"); if (cur_sp != null) { try {//w ww .j av a 2s.c o m cur_sp.moveToFirst(); // insert dummy item with no data as to avoid pre-selection GliderList.add(""); for (int i = 0; i < cur_sp.getCount(); i++) { GliderList.add(cur_sp.getString(cur_sp.getColumnIndexOrThrow(GliderLogTables.G_REGISTRATION))); cur_sp.moveToNext(); } } finally { if (!cur_sp.isClosed()) { cur_sp.close(); } } } }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private boolean _fillLrnDay() { if (mLrnCount == 0) { return false; }// w w w. j av a 2 s. com if (!mLrnDayQueue.isEmpty()) { return true; } while (mLrnDids.size() > 0) { long did = mLrnDids.getFirst(); // fill the queue with the current did mLrnDayQueue.clear(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery("SELECT id FROM cards WHERE did = " + did + " AND queue = 3 AND due <= " + mToday + " LIMIT " + mQueueLimit, null); while (cur.moveToNext()) { mLrnDayQueue.add(cur.getLong(0)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (mLrnDayQueue.size() > 0) { // order Random r = new Random(); r.setSeed(mToday); Collections.shuffle(mLrnDayQueue, r); // is the current did empty? if (mLrnDayQueue.size() < mQueueLimit) { mLrnDids.remove(); } return true; } // nothing left in the deck; move to next mLrnDids.remove(); } return false; }
From source file:org.awesomeapp.messenger.ui.ConversationView.java
private void updateSessionInfo(Cursor c) { if (c != null && (!c.isClosed())) { mProviderId = c.getLong(PROVIDER_COLUMN); mAccountId = c.getLong(ACCOUNT_COLUMN); mPresenceStatus = c.getInt(PRESENCE_STATUS_COLUMN); mContactType = c.getInt(TYPE_COLUMN); mRemoteNickname = c.getString(NICKNAME_COLUMN); mRemoteAddress = c.getString(USERNAME_COLUMN); mSubscriptionType = c.getInt(SUBSCRIPTION_TYPE_COLUMN); mSubscriptionStatus = c.getInt(SUBSCRIPTION_STATUS_COLUMN); if (mSubscriptionStatus == Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING) { // bindSubscription(mProviderId, mRemoteAddress); new android.support.v7.app.AlertDialog.Builder(mActivity) .setTitle(mActivity.getString(R.string.add_friends)) .setMessage(mContext.getString(R.string.subscription_notify_text, mRemoteAddress)) .setPositiveButton(mActivity.getString(R.string.accept_invitation), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { approveSubscription(); }/*from w w w .j a va 2 s . co m*/ }) .setNegativeButton(mActivity.getString(R.string.decline_subscription), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert).show(); } } }