List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:info.guardianproject.otr.app.im.app.ChatView.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 ((mSubscriptionType == Imps.Contacts.SUBSCRIPTION_TYPE_FROM) && (mSubscriptionStatus == Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING)) { bindSubscription(mProviderId, mRemoteAddress); }/* w w w. j ava 2 s .c om*/ } }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get the map of article IDs to its update date from DB * * @param selection A filter declaring which articles should be considered, formatted as an SQL WHERE clause * (excluding/*from ww w. j a v a 2 s . c om*/ * the WHERE * itself). Passing null will return all rows. * @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, * in * order * that they appear in the selection. The values will be bound as Strings. * @return map of unread article IDs to its update date (may be {@code null}) */ @SuppressLint("UseSparseArrays") public Map<Integer, Long> getArticleIdUpdatedMap(String selection, String[] selectionArgs) { Map<Integer, Long> ret = null; if (!isDBAvailable()) return null; Cursor c = null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); try { c = db.query(TABLE_ARTICLES, new String[] { "_id", "updateDate" }, selection, selectionArgs, null, null, null); ret = new HashMap<>(c.getCount()); while (c.moveToNext()) { ret.put(c.getInt(0), c.getLong(1)); } } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:com.hichinaschool.flashcards.libanki.Collection.java
public ArrayList<Long> genCards(long[] nids) { // build map of (nid,ord) so we don't create dupes String snids = Utils.ids2str(nids); HashMap<Long, HashMap<Integer, Long>> have = new HashMap<Long, HashMap<Integer, Long>>(); HashMap<Long, Long> dids = new HashMap<Long, Long>(); Cursor cur = null; try {/* w w w.j a va 2 s .co m*/ cur = mDb.getDatabase().rawQuery("SELECT id, nid, ord, did FROM cards WHERE nid IN " + snids, null); while (cur.moveToNext()) { // existing cards long nid = cur.getLong(1); if (!have.containsKey(nid)) { have.put(nid, new HashMap<Integer, Long>()); } have.get(nid).put(cur.getInt(2), cur.getLong(0)); // and their dids long did = cur.getLong(3); if (dids.containsKey(nid)) { if (dids.get(nid) != 0 && dids.get(nid) != did) { // cards are in two or more different decks; revert to model default dids.put(nid, 0l); } } else { // first card or multiple cards in same deck dids.put(nid, did); } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // build cards for each note ArrayList<Object[]> data = new ArrayList<Object[]>(); long ts = Utils.maxID(mDb); long now = Utils.intNow(); ArrayList<Long> rem = new ArrayList<Long>(); int usn = usn(); cur = null; try { cur = mDb.getDatabase().rawQuery("SELECT id, mid, flds FROM notes WHERE id IN " + snids, null); while (cur.moveToNext()) { JSONObject model = mModels.get(cur.getLong(1)); ArrayList<Integer> avail = mModels.availOrds(model, cur.getString(2)); long nid = cur.getLong(0); long did = dids.get(nid); if (did == 0) { did = model.getLong("did"); } // add any missing cards for (JSONObject t : _tmplsFromOrds(model, avail)) { int tord = t.getInt("ord"); boolean doHave = have.containsKey(nid) && have.get(nid).containsKey(tord); if (!doHave) { // check deck is not a cram deck long ndid; try { ndid = t.getLong("did"); if (ndid != 0) { did = ndid; } } catch (JSONException e) { // do nothing } if (getDecks().isDyn(did)) { did = 1; } // if the deck doesn't exist, use default instead did = mDecks.get(did).getLong("id"); // we'd like to use the same due# as sibling cards, but we can't retrieve that quickly, so we // give it a new id instead data.add(new Object[] { ts, nid, did, tord, now, usn, nextID("pos") }); ts += 1; } } // note any cards that need removing if (have.containsKey(nid)) { for (Map.Entry<Integer, Long> n : have.get(nid).entrySet()) { if (!avail.contains(n.getKey())) { rem.add(n.getValue()); } } } } } catch (JSONException e) { throw new RuntimeException(e); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // bulk update mDb.executeMany("INSERT INTO cards VALUES (?,?,?,?,?,?,0,0,?,0,0,0,0,0,0,0,0,\"\")", data); return rem; }
From source file:org.ttrssreader.controllers.DBHelper.java
Set<Label> getLabelsForArticle(int articleId) { if (!isDBAvailable()) return new HashSet<>(); // @formatter:off String sql = "SELECT f._id, f.title, 0 checked FROM " + TABLE_FEEDS + " f " + " WHERE f._id <= -11 AND" + " NOT EXISTS (SELECT * FROM " + TABLE_ARTICLES2LABELS + " a2l where f._id = a2l.labelId AND a2l.articleId = " + articleId + ")" + " UNION" + " SELECT f._id, f.title, 1 checked FROM " + TABLE_FEEDS + " f, " + TABLE_ARTICLES2LABELS + " a2l " + " WHERE f._id <= -11 AND f._id = a2l.labelId AND a2l.articleId = " + articleId; // @formatter:on SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true);//from w w w . ja v a 2 s.c om Cursor c = null; try { c = db.rawQuery(sql, null); Set<Label> ret = new HashSet<>(c.getCount()); while (c.moveToNext()) { Label label = new Label(); label.id = c.getInt(0); label.caption = c.getString(1); label.checked = c.getInt(2) == 1; ret.add(label); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } }
From source file:com.aware.Aware.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { DEBUG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_FLAG).equals("true"); TAG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG).length() > 0 ? Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG) : TAG;//from ww w.j av a2 s.c o m if (Aware.DEBUG) Log.d(TAG, "AWARE framework is active..."); startAllServices(); //Only the client keeps the plugins running and checks for updates if (getPackageName().equals("com.aware")) { Cursor enabled_plugins = getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_STATUS + "=" + Aware_Plugin.STATUS_PLUGIN_ON, null, null); if (enabled_plugins != null && enabled_plugins.moveToFirst()) { do { startPlugin(getApplicationContext(), enabled_plugins .getString(enabled_plugins.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME))); } while (enabled_plugins.moveToNext()); } if (enabled_plugins != null && !enabled_plugins.isClosed()) enabled_plugins.close(); if (Aware.getSetting(getApplicationContext(), Aware_Preferences.AWARE_AUTO_UPDATE).equals("true")) { if (aware_preferences.getLong(PREF_LAST_UPDATE, 0) == 0 || (aware_preferences.getLong(PREF_LAST_UPDATE, 0) > 0 && System.currentTimeMillis() - aware_preferences.getLong(PREF_LAST_UPDATE, 0) > 6 * 60 * 60 * 1000)) { //check every 6h new Update_Check().execute(); SharedPreferences.Editor editor = aware_preferences.edit(); editor.putLong(PREF_LAST_UPDATE, System.currentTimeMillis()); editor.commit(); } } } if (Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE).equals("true")) { int frequency_webservice = Integer.parseInt( Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE)); if (frequency_webservice == 0) { if (DEBUG) { Log.d(TAG, "Data sync is disabled."); } alarmManager.cancel(webserviceUploadIntent); } else if (frequency_webservice > 0) { //Fixed: set alarm only once if not set yet. if (aware_preferences.getLong(PREF_LAST_SYNC, 0) == 0 || (aware_preferences.getLong(PREF_LAST_SYNC, 0) > 0 && System.currentTimeMillis() - aware_preferences.getLong(PREF_LAST_SYNC, 0) > frequency_webservice * 60 * 1000)) { if (DEBUG) { Log.d(TAG, "Data sync every " + frequency_webservice + " minute(s)"); } SharedPreferences.Editor editor = aware_preferences.edit(); editor.putLong(PREF_LAST_SYNC, System.currentTimeMillis()); editor.commit(); alarmManager.setInexactRepeating(AlarmManager.RTC, aware_preferences.getLong(PREF_LAST_SYNC, 0), frequency_webservice * 60 * 1000, webserviceUploadIntent); } } //Check if study is open or still exists new Study_Check().execute(); } if (!Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_CLEAN_OLD_DATA) .equals("0")) { Intent dataCleaning = new Intent(ACTION_AWARE_SPACE_MAINTENANCE); awareContext.sendBroadcast(dataCleaning); } } else { //Turn off all enabled plugins Cursor enabled_plugins = getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_STATUS + "=" + Aware_Plugin.STATUS_PLUGIN_ON, null, null); if (enabled_plugins != null && enabled_plugins.moveToFirst()) { do { stopPlugin(getApplicationContext(), enabled_plugins .getString(enabled_plugins.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME))); } while (enabled_plugins.moveToNext()); enabled_plugins.close(); } if (enabled_plugins != null && !enabled_plugins.isClosed()) enabled_plugins.close(); if (Aware.DEBUG) Log.w(TAG, "AWARE plugins disabled..."); } return START_STICKY; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * set read status in DB for given category/feed * * @param id category/feed ID//from w ww . jav a 2s. co m * @param isCategory if set to {@code true}, then given id is category * ID, otherwise - feed ID * @return collection of article IDs, which was marked as read or {@code null} if nothing was changed */ Collection<Integer> markRead(int id, boolean isCategory) { Set<Integer> ret = null; if (!isDBAvailable()) return null; StringBuilder where = new StringBuilder(); StringBuilder feedIds = new StringBuilder(); switch (id) { case Data.VCAT_ALL: where.append(" 1 "); // Select everything... break; case Data.VCAT_FRESH: long time = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge(); where.append(" updateDate > ").append(time); break; case Data.VCAT_PUB: where.append(" isPublished > 0 "); break; case Data.VCAT_STAR: where.append(" isStarred > 0 "); break; default: if (isCategory) { feedIds.append("SELECT _id FROM ").append(TABLE_FEEDS).append(" WHERE categoryId=").append(id); } else { feedIds.append(id); } where.append(" feedId IN (").append(feedIds).append(") "); break; } where.append(" and isUnread>0 "); Cursor c = null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); try { // select id from articles where categoryId in (...) c = db.query(TABLE_ARTICLES, new String[] { "_id" }, where.toString(), null, null, null, null); int count = c.getCount(); if (count > 0) { ret = new HashSet<>(count); while (c.moveToNext()) { ret.add(c.getInt(0)); } } } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } if (ret != null && !ret.isEmpty()) { // TODO Check access markArticles(ret, "isUnread", 0); } return ret; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get remote files for given articles//w w w . j a v a 2 s . com * * @param whereClause the WHERE clause to apply when selecting. * @param whereArgs You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * @param uniqOnly if set to {@code true}, then only remote files, which are referenced by given articles only * will be * returned, otherwise all remote files referenced by given articles will be found (even those, * which are * referenced also by some other articles) * @return collection of remote file objects from DB or {@code null} */ private Collection<RemoteFile> getRemoteFilesForArticles(String whereClause, String[] whereArgs, boolean uniqOnly) { if (!isDBAvailable()) return null; ArrayList<RemoteFile> rfs = null; StringBuilder uniqRestriction = new StringBuilder(); String[] queryArgs = whereArgs; if (uniqOnly) { // @formatter:off uniqRestriction.append(" AND m.remotefileId NOT IN (").append(" SELECT remotefileId") .append(" FROM ").append(TABLE_REMOTEFILE2ARTICLE) .append(" WHERE remotefileId IN (").append(" SELECT remotefileId") .append(" FROM ").append(TABLE_REMOTEFILE2ARTICLE) .append(" WHERE articleId IN (").append(" SELECT _id") .append(" FROM ").append(TABLE_ARTICLES).append(" WHERE ") .append(whereClause).append(" )").append(" GROUP BY remotefileId)") .append(" AND articleId NOT IN (").append(" SELECT _id") .append(" FROM ").append(TABLE_ARTICLES).append(" WHERE ") .append(whereClause).append(" )").append(" GROUP by remotefileId)"); // @formatter:on // because we are using whereClause twice in uniqRestriction, then we should also extend queryArgs, // which will be used in query if (whereArgs != null) { int initialLength = whereArgs.length; queryArgs = new String[initialLength * 3]; for (int i = 0; i < 3; i++) { System.arraycopy(whereArgs, 0, queryArgs, i * initialLength, initialLength); } } } StringBuilder query = new StringBuilder(); // @formatter:off query.append(" SELECT r.*").append(" FROM ").append(TABLE_REMOTEFILES + " r,") .append(TABLE_REMOTEFILE2ARTICLE + " m, ").append(TABLE_ARTICLES + " a") .append(" WHERE m.remotefileId=r.id").append(" AND m.articleId=a._id") .append(" AND a._id IN (").append(" SELECT _id FROM ").append(TABLE_ARTICLES) .append(" WHERE ").append(whereClause).append(" )").append(uniqRestriction) .append(" GROUP BY r.id"); // @formatter:on SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { long time = System.currentTimeMillis(); c = db.rawQuery(query.toString(), queryArgs); rfs = new ArrayList<>(); while (c.moveToNext()) { rfs.add(handleRemoteFileCursor(c)); } Log.d(TAG, "Query in getRemoteFilesForArticles took " + (System.currentTimeMillis() - time) + "ms... (remotefiles: " + rfs.size() + ")"); } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return rfs; }
From source file:org.ttrssreader.controllers.DBHelper.java
public ArrayList<Article> queryArticlesForImagecache() { if (!isDBAvailable()) return null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true);/*from w w w . ja v a 2 s . c om*/ Cursor c = null; try { c = db.query(TABLE_ARTICLES, new String[] { "_id", "content", "attachments" }, "cachedImages IS NULL AND isUnread>0", null, null, null, null, "1000"); ArrayList<Article> ret = new ArrayList<>(c.getCount()); while (c.moveToNext()) { Article a = new Article(); a.id = c.getInt(0); a.content = c.getString(1); a.attachments = parseAttachments(c.getString(2)); ret.add(a); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } }
From source file:com.hichinaschool.flashcards.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 {// w w w . j a va2 s . 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") == Sched.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)); } // 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", false)); // 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) { Log.e(AnkiDroidApp.TAG, "doInBackgroundCheckDatabase - RuntimeException on marking card: " + e); AnkiDroidApp.saveExceptionReportFile(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) { modSchema(false); } // TODO: report problems return (long) ((oldSize - newSize) / 1024); }
From source file:com.aware.Aware.java
/** * Insert / Update settings of the framework * @param key/* w w w .jav a 2 s . c o m*/ * @param value */ public static void setSetting(Context context, String key, Object value) { boolean is_restricted_package = true; ArrayList<String> global_settings = new ArrayList<String>(); global_settings.add("debug_flag"); global_settings.add("debug_tag"); global_settings.add("study_id"); global_settings.add("study_start"); if (global_settings.contains(key)) { is_restricted_package = false; } //Only AWARE client can change the device ID if needed if (key.equals("device_id") && !context.getPackageName().equals("com.aware")) { return; } ContentValues setting = new ContentValues(); setting.put(Aware_Settings.SETTING_KEY, key); setting.put(Aware_Settings.SETTING_VALUE, value.toString()); setting.put(Aware_Settings.SETTING_PACKAGE_NAME, context.getPackageName()); Cursor qry = context.getContentResolver().query(Aware_Settings.CONTENT_URI, null, Aware_Settings.SETTING_KEY + " LIKE '" + key + "'" + (is_restricted_package ? " AND " + Aware_Settings.SETTING_PACKAGE_NAME + " LIKE '" + context.getPackageName() + "'" : ""), null, null); //update if (qry != null && qry.moveToFirst()) { try { if (!qry.getString(qry.getColumnIndex(Aware_Settings.SETTING_VALUE)).equals(value.toString())) { context.getContentResolver().update(Aware_Settings.CONTENT_URI, setting, Aware_Settings.SETTING_ID + "=" + qry.getInt(qry.getColumnIndex(Aware_Settings.SETTING_ID)), null); if (Aware.DEBUG) Log.d(Aware.TAG, "Updated: " + key + "=" + value); } } catch (SQLiteException e) { if (Aware.DEBUG) Log.d(TAG, e.getMessage()); } catch (SQLException e) { if (Aware.DEBUG) Log.d(TAG, e.getMessage()); } //insert } else { try { context.getContentResolver().insert(Aware_Settings.CONTENT_URI, setting); if (Aware.DEBUG) Log.d(Aware.TAG, "Added: " + key + "=" + value); } catch (SQLiteException e) { if (Aware.DEBUG) Log.d(TAG, e.getMessage()); } catch (SQLException e) { if (Aware.DEBUG) Log.d(TAG, e.getMessage()); } } if (qry != null && !qry.isClosed()) qry.close(); }