List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:org.ttrssreader.controllers.DBHelper.java
public synchronized void initialize(final Context context) { this.contextRef = new WeakReference<>(context); // TODO: Remove leak of context new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { // Check if deleteDB is scheduled or if DeleteOnStartup is set if (Controller.getInstance().isDeleteDBScheduled()) { if (deleteDB(context)) { Controller.getInstance().setDeleteDBScheduled(false); initializeDBHelper(); return null; // Don't need to check if DB is corrupted, it is NEW! }//from w ww. ja v a2s . com } // Initialize DB if (!initialized) { initializeDBHelper(); } else if (getOpenHelper() == null) { initializeDBHelper(); } else { return null; // DB was already initialized, no need to check anything. } // Test if DB is accessible, backup and delete if not if (initialized) { Cursor c = null; readLock(true); try { // Try to access the DB c = getOpenHelper().getReadableDatabase() .rawQuery("SELECT COUNT(*) FROM " + TABLE_CATEGORIES, null); c.getCount(); if (c.moveToFirst()) c.getInt(0); } catch (Exception e) { Log.e(TAG, "Database was corrupted, creating a new one...", e); closeDB(); File dbFile = context.getDatabasePath(DATABASE_NAME); if (dbFile.delete()) initializeDBHelper(); ErrorDialog.getInstance( "The Database was corrupted and had to be recreated. If this happened more than once to you please let me know under what circumstances this happened."); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } } return null; } }.execute(); }
From source file:com.ichi2.libanki.Sched.java
private boolean _fillLrn() { if (mLrnCount == 0) { return false; }// w ww . j a v a 2 s . c om 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 Comparator<long[]>() { @Override public int compare(long[] lhs, long[] rhs) { return Long.valueOf(lhs[0]).compareTo(rhs[0]); } }); return !mLrnQueue.isEmpty(); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public int getTableFlightsCnt(String act_date, int mode) { // Mode = 0 => return # flights in table, Mode = 1 => remove old reported flights int res = 0;/*from www . j a v a 2s . c o m*/ Cursor cur_fc = null; Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT; String[] projection = { GliderLogTables.F_ID, GliderLogTables.F_DATE }; String selection = GliderLogTables.F_DATE + " < '" + act_date + "'"; // add selection for delete operation if (mode > 0) { if (mode == 1) { selection += " AND ((" + GliderLogTables.F_SENT + " = 1 AND " + GliderLogTables.F_ACK + " = 1" + " AND " + GliderLogTables.F_HID + " > 0) OR (" + GliderLogTables.F_DEL + " = 1 AND " + GliderLogTables.F_HID + " = 0))"; } res = getContentResolver().delete(uri, selection, null); } else { cur_fc = getContentResolver().query(uri, projection, selection, null, null); if (cur_fc != null) { try { res = cur_fc.getCount(); } finally { if (!cur_fc.isClosed()) { cur_fc.close(); } } } } return res; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * Set unread counters for feeds and categories according to real amount of unread articles. *//*w ww .j a va 2s . c o m*/ void calculateCounters() { if (!isDBAvailable()) return; long time = System.currentTimeMillis(); int total = 0; Cursor c = null; SQLiteDatabase db = getOpenHelper().getWritableDatabase(); writeLock(true); db.beginTransaction(); try { ContentValues cv = new ContentValues(1); // First of all, reset all feeds and all categories to unread=0 cv.put("unread", 0); db.update(TABLE_FEEDS, cv, null, null); db.update(TABLE_CATEGORIES, cv, null, null); // Count all feeds where unread articles exist try { // select feedId, count(*) from articles where isUnread>0 group by feedId c = db.query(TABLE_ARTICLES, new String[] { "feedId", "count(*)" }, "isUnread>0", null, "feedId", null, null, null); // update feeds while (c.moveToNext()) { int feedId = c.getInt(0); int unreadCount = c.getInt(1); total += unreadCount; cv.put("unread", unreadCount); db.update(TABLE_FEEDS, cv, "_id=" + feedId, null); } } finally { if (c != null && !c.isClosed()) c.close(); } // Count all categories where feeds with unread articles exist try { // select categoryId, sum(unread) from feeds where categoryId >= 0 group by categoryId c = db.query(TABLE_FEEDS, new String[] { "categoryId", "sum(unread)" }, "categoryId>=0", null, "categoryId", null, null, null); // update real categories while (c.moveToNext()) { int categoryId = c.getInt(0); int unreadCount = c.getInt(1); cv.put("unread", unreadCount); db.update(TABLE_CATEGORIES, cv, "_id=" + categoryId, null); } } finally { if (c != null && !c.isClosed()) c.close(); } // Count special categories cv.put("unread", total); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_ALL, null); cv.put("unread", getUnreadCount(Data.VCAT_FRESH, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_FRESH, null); cv.put("unread", getUnreadCount(Data.VCAT_PUB, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_PUB, null); cv.put("unread", getUnreadCount(Data.VCAT_STAR, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_STAR, null); db.setTransactionSuccessful(); } finally { db.endTransaction(); writeLock(false); } Log.i(TAG, String.format("Fixed counters, total unread: %s (took %sms)", total, (System.currentTimeMillis() - time))); }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public void addItemSpinner_1() { Uri uri = FlightsContentProvider.CONTENT_URI_MEMBER; String[] projection = { GliderLogTables.M_ID, GliderLogTables.M_2_NAME, GliderLogTables.M_3_NAME, GliderLogTables.M_1_NAME, GliderLogTables.M_INSTRUCTION }; Cursor cur_sp = getContentResolver().query(uri, projection, null, null, GliderLogTables.M_1_NAME + " ASC"); if (cur_sp != null) { try {/* w w w . jav a 2 s. c om*/ cur_sp.moveToFirst(); // insert dummy item with no data as to avoid pre-selection MemberList.add(""); MemberIndexList.add(""); for (int i = 0; i < cur_sp.getCount(); i++) { String tmp = cur_sp.getString(cur_sp.getColumnIndexOrThrow(GliderLogTables.M_1_NAME)) + " " + cur_sp.getString(cur_sp.getColumnIndexOrThrow(GliderLogTables.M_2_NAME)) + " " + cur_sp.getString(cur_sp.getColumnIndexOrThrow(GliderLogTables.M_3_NAME)); MemberList.add(tmp.replaceAll("\\s+", " ")); MemberIndexList.add(cur_sp.getString(cur_sp.getColumnIndexOrThrow(GliderLogTables.M_ID))); cur_sp.moveToNext(); } } finally { if (!cur_sp.isClosed()) { cur_sp.close(); } } } }
From source file:de.ub0r.android.callmeter.data.RuleMatcher.java
/** * Match all unmatched logs./*from w ww. j a v a 2 s . c o m*/ * * @param context {@link Context} * @param showStatus post status to dialog/handler * @return true if a log was matched */ static synchronized boolean match(final Context context, final boolean showStatus) { Log.d(TAG, "match(ctx, ", showStatus, ")"); long start = System.currentTimeMillis(); boolean ret = false; load(context); final ContentResolver cr = context.getContentResolver(); final Cursor cursor = cr.query(DataProvider.Logs.CONTENT_URI, DataProvider.Logs.PROJECTION, DataProvider.Logs.PLAN_ID + " = " + DataProvider.NO_ID, null, DataProvider.Logs.DATE + " ASC"); if (cursor != null && cursor.moveToFirst()) { final int l = cursor.getCount(); Handler h; if (showStatus) { h = Plans.getHandler(); if (h != null) { final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER); m.arg1 = 0; m.arg2 = l; m.sendToTarget(); } } try { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int i = 1; do { ret |= matchLog(cr, ops, cursor); if (i % PROGRESS_STEPS == 0 || (i < PROGRESS_STEPS && i % CallMeter.TEN == 0)) { h = Plans.getHandler(); if (h != null) { final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER); m.arg1 = i; m.arg2 = l; Log.d(TAG, "send progress: ", i, "/", l); m.sendToTarget(); } else { Log.d(TAG, "send progress: ", i, " handler=null"); } Log.d(TAG, "save logs.."); cr.applyBatch(DataProvider.AUTHORITY, ops); ops.clear(); Log.d(TAG, "sleeping.."); try { Thread.sleep(CallMeter.MILLIS); } catch (InterruptedException e) { Log.e(TAG, "sleep interrupted", e); } Log.d(TAG, "sleep finished"); } ++i; } while (cursor.moveToNext()); if (ops.size() > 0) { cr.applyBatch(DataProvider.AUTHORITY, ops); } } catch (IllegalStateException e) { Log.e(TAG, "illegal state in RuleMatcher's loop", e); } catch (OperationApplicationException e) { Log.e(TAG, "illegal operation in RuleMatcher's loop", e); } catch (RemoteException e) { Log.e(TAG, "remote exception in RuleMatcher's loop", e); } } try { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } catch (IllegalStateException e) { Log.e(TAG, "illegal state while closing cursor", e); } if (ret) { final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); final boolean a80 = p.getBoolean(Preferences.PREFS_ALERT80, true); final boolean a100 = p.getBoolean(Preferences.PREFS_ALERT100, true); // check for alerts if ((a80 || a100) && plans != null && plans.size() > 0) { final long now = System.currentTimeMillis(); int alert = 0; Plan alertPlan = null; int l = plans.size(); for (int i = 0; i < l; i++) { final Plan plan = plans.valueAt(i); if (plan == null) { continue; } if (plan.nextAlert > now) { Log.d(TAG, "%s: skip alert until: %d now=%d", plan, plan.nextAlert, now); continue; } int used = DataProvider.Plans.getUsed(plan.type, plan.limitType, plan.billedAmount, plan.billedCost); int usedRate = plan.limit > 0 ? (int) ((used * CallMeter.HUNDRED) / plan.limit) : 0; if (a100 && usedRate >= CallMeter.HUNDRED) { alert = usedRate; alertPlan = plan; } else if (a80 && alert < CallMeter.EIGHTY && usedRate >= CallMeter.EIGHTY) { alert = usedRate; alertPlan = plan; } } if (alert > 0) { final NotificationManager mNotificationMgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final String t = String.format(context.getString(R.string.alerts_message), alertPlan.name, alert); NotificationCompat.Builder b = new NotificationCompat.Builder(context); b.setSmallIcon(android.R.drawable.stat_notify_error); b.setTicker(t); b.setWhen(now); b.setContentTitle(context.getString(R.string.alerts_title)); b.setContentText(t); Intent i = new Intent(context, Plans.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); mNotificationMgr.notify(0, b.build()); // set nextAlert to beginning of next day Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); alertPlan.nextAlert = cal.getTimeInMillis(); final ContentValues cv = new ContentValues(); cv.put(DataProvider.Plans.NEXT_ALERT, alertPlan.nextAlert); cr.update(DataProvider.Plans.CONTENT_URI, cv, DataProvider.Plans.ID + " = ?", new String[] { String.valueOf(alertPlan.id) }); } } } long end = System.currentTimeMillis(); Log.i(TAG, "match(): ", end - start, "ms"); return ret; }
From source file:org.opendatakit.common.android.task.InitializationTask.java
/** * Remove definitions from the Forms database that are no longer present on * disk.//from w w w .j a v a 2 s.co m */ private final void removeStaleFormInfo(List<File> discoveredFormDefDirs) { Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY); String completionString = appContext.getString(R.string.searching_for_deleted_forms); publishProgress(completionString, null); WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " begin"); ArrayList<Uri> badEntries = new ArrayList<Uri>(); Cursor c = null; try { c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null, null, null, null); if (c == null) { WebLogger.getLogger(appName).w(t, "removeStaleFormInfo " + appName + " null cursor returned from query."); return; } if (c.moveToFirst()) { do { String tableId = ODKCursorUtils.getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); String formId = ODKCursorUtils.getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); Uri otherUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), tableId), formId); String examString = appContext.getString(R.string.examining_form, tableId, formId); publishProgress(examString, null); String formDir = ODKFileUtils.getFormFolder(appName, tableId, formId); File f = new File(formDir); File formDefJson = new File(f, ODKFileUtils.FORMDEF_JSON_FILENAME); if (!f.exists() || !f.isDirectory() || !formDefJson.exists() || !formDefJson.isFile()) { // the form definition does not exist badEntries.add(otherUri); continue; } else { // //////////////////////////////// // formdef.json exists. See if it is // unchanged... String json_md5 = ODKCursorUtils.getIndexAsString(c, c.getColumnIndex(FormsColumns.JSON_MD5_HASH)); String fileMd5 = ODKFileUtils.getMd5Hash(appName, formDefJson); if (json_md5.equals(fileMd5)) { // it is unchanged -- no need to rescan it discoveredFormDefDirs.remove(f); } } } while (c.moveToNext()); } } catch (Exception e) { WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString()); WebLogger.getLogger(appName).printStackTrace(e); } finally { if (c != null && !c.isClosed()) { c.close(); } } // delete the other entries (and directories) for (Uri badUri : badEntries) { WebLogger.getLogger(appName).i(t, "removeStaleFormInfo: " + appName + " deleting: " + badUri.toString()); try { appContext.getContentResolver().delete(badUri, null, null); } catch (Exception e) { WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString()); WebLogger.getLogger(appName).printStackTrace(e); // and continue -- don't throw an error } } WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " end"); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Retrieve the list of user-defined columns for a tableId using the metadata * for that table. Returns the unit-of-retention and non-unit-of-retention * (grouping) columns./* w w w.j a v a 2 s . c o m*/ * * @param db * @param tableId * @return */ public ArrayList<Column> getUserDefinedColumns(SQLiteDatabase db, String tableId) { ArrayList<Column> userDefinedColumns = new ArrayList<Column>(); String selection = ColumnDefinitionsColumns.TABLE_ID + "=?"; String[] selectionArgs = { tableId }; //@formatter:off String[] cols = { ColumnDefinitionsColumns.ELEMENT_KEY, ColumnDefinitionsColumns.ELEMENT_NAME, ColumnDefinitionsColumns.ELEMENT_TYPE, ColumnDefinitionsColumns.LIST_CHILD_ELEMENT_KEYS }; //@formatter:on Cursor c = null; try { c = db.query(DatabaseConstants.COLUMN_DEFINITIONS_TABLE_NAME, cols, selection, selectionArgs, null, null, ColumnDefinitionsColumns.ELEMENT_KEY + " ASC"); int elemKeyIndex = c.getColumnIndexOrThrow(ColumnDefinitionsColumns.ELEMENT_KEY); int elemNameIndex = c.getColumnIndexOrThrow(ColumnDefinitionsColumns.ELEMENT_NAME); int elemTypeIndex = c.getColumnIndexOrThrow(ColumnDefinitionsColumns.ELEMENT_TYPE); int listChildrenIndex = c.getColumnIndexOrThrow(ColumnDefinitionsColumns.LIST_CHILD_ELEMENT_KEYS); c.moveToFirst(); while (!c.isAfterLast()) { String elementKey = getIndexAsString(c, elemKeyIndex); String elementName = getIndexAsString(c, elemNameIndex); String elementType = getIndexAsString(c, elemTypeIndex); String listOfChildren = getIndexAsString(c, listChildrenIndex); userDefinedColumns.add(new Column(elementKey, elementName, elementType, listOfChildren)); c.moveToNext(); } } finally { if (c != null && !c.isClosed()) { c.close(); } } return userDefinedColumns; }
From source file:com.ichi2.libanki.Sched.java
/** * Sibling spacing//w w w . j a v a2 s . co m * ******************** */ private void _burySiblings(Card card) { LinkedList<Long> toBury = new LinkedList<Long>(); JSONObject nconf = _newConf(card); boolean buryNew = nconf.optBoolean("bury", true); JSONObject rconf = _revConf(card); boolean buryRev = rconf.optBoolean("bury", true); // loop through and remove from queues Cursor cur = null; try { cur = mCol.getDb().getDatabase() .rawQuery(String.format(Locale.US, "select id, queue from cards where nid=%d and id!=%d " + "and (queue=0 or (queue=2 and due<=%d))", new Object[] { card.getNid(), card.getId(), mToday }), null); while (cur.moveToNext()) { long cid = cur.getLong(0); int queue = cur.getInt(1); if (queue == 2) { if (buryRev) { toBury.add(cid); } // if bury disabled, we still discard to give same-day spacing mRevQueue.remove(cid); } else { // if bury is disabled, we still discard to give same-day spacing if (buryNew) { toBury.add(cid); } mNewQueue.remove(cid); } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // then bury if (toBury.size() > 0) { mCol.getDb().execute("update cards set queue=-2,mod=?,usn=? where id in " + Utils.ids2str(toBury), new Object[] { Utils.now(), mCol.usn() }); mCol.log(toBury); } }