List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:com.hichinaschool.flashcards.libanki.Stats.java
/** * Reps and time spent/*from ww w .j av a2 s.c o m*/ * *********************************************************************************************** */ public boolean calculateDone(int type, boolean reps) { mType = type; mBackwards = true; if (reps) { mTitle = R.string.stats_review_count; mAxisTitles = new int[] { type, R.string.stats_answers }; } else { mTitle = R.string.stats_review_time; } mValueLabels = new int[] { R.string.statistics_learn, R.string.statistics_relearn, R.string.statistics_young, R.string.statistics_mature, R.string.statistics_cram }; mColors = new int[] { R.color.stats_learn, R.color.stats_relearn, R.color.stats_young, R.color.stats_mature, R.color.stats_cram }; int num = 0; int chunk = 0; switch (type) { case TYPE_MONTH: num = 31; chunk = 1; break; case TYPE_YEAR: num = 52; chunk = 7; break; case TYPE_LIFE: num = -1; chunk = 30; break; } ArrayList<String> lims = new ArrayList<String>(); if (num != -1) { lims.add("id > " + ((mCol.getSched().getDayCutoff() - ((num + 1) * chunk * 86400)) * 1000)); } String lim = _revlogLimit().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lims.add(lim); } if (lims.size() > 0) { lim = "WHERE "; while (lims.size() > 1) { lim += lims.remove(0) + " AND "; } lim += lims.remove(0); } else { lim = ""; } String ti; String tf; if (!reps) { ti = "time/1000"; if (mType == 0) { tf = "/60.0"; // minutes mAxisTitles = new int[] { type, R.string.stats_minutes }; } else { tf = "/3600.0"; // hours mAxisTitles = new int[] { type, R.string.stats_hours }; } } else { ti = "1"; tf = ""; } ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase() .rawQuery("SELECT (cast((id/1000 - " + mCol.getSched().getDayCutoff() + ") / 86400.0 AS INT))/" + chunk + " AS day, " + "sum(CASE WHEN type = 0 THEN " + ti + " ELSE 0 END)" + tf + ", " // lrn + "sum(CASE WHEN type = 1 AND lastIvl < 21 THEN " + ti + " ELSE 0 END)" + tf + ", " // yng + "sum(CASE WHEN type = 1 AND lastIvl >= 21 THEN " + ti + " ELSE 0 END)" + tf + ", " // mtr + "sum(CASE WHEN type = 2 THEN " + ti + " ELSE 0 END)" + tf + ", " // lapse + "sum(CASE WHEN type = 3 THEN " + ti + " ELSE 0 END)" + tf // cram + " FROM revlog " + lim + " GROUP BY day ORDER BY day", null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(4), cur.getDouble(2), cur.getDouble(3), cur.getDouble(5) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // small adjustment for a proper chartbuilding with achartengine if (type != TYPE_LIFE && (list.size() == 0 || list.get(0)[0] > -num)) { list.add(0, new double[] { -num, 0, 0, 0, 0, 0 }); } else if (type == TYPE_LIFE && list.size() == 0) { list.add(0, new double[] { -12, 0, 0, 0, 0, 0 }); } if (list.get(list.size() - 1)[0] < 0) { list.add(new double[] { 0, 0, 0, 0, 0, 0 }); } mSeriesList = new double[6][list.size()]; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); mSeriesList[0][i] = data[0]; // day mSeriesList[1][i] = data[1] + data[2] + data[3] + data[4] + data[5]; // lrn mSeriesList[2][i] = data[2] + data[3] + data[4] + data[5]; // relearn mSeriesList[3][i] = data[3] + data[4] + data[5]; // young mSeriesList[4][i] = data[4] + data[5]; // mature mSeriesList[5][i] = data[5]; // cram } return list.size() > 0; }
From source file:com.xorcode.andtweet.TweetListActivity.java
@Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info; try {// w ww .j a va 2 s . c o m info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } mCurrentId = info.id; Uri uri; Cursor c; switch (item.getItemId()) { case CONTEXT_MENU_ITEM_REPLY: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID }, null, null, null); try { c.moveToFirst(); String reply = "@" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; long replyId = c.getLong(c.getColumnIndex(Tweets._ID)); mTweetEditor.startEditing(reply, replyId); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_RETWEET: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder message = new StringBuilder(); String reply = "RT @" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; message.append(reply); CharSequence text = c.getString(c.getColumnIndex(Tweets.MESSAGE)); int len = 140 - reply.length() - 3; if (text.length() < len) { len = text.length(); } message.append(text, 0, len); if (message.length() == 137) { message.append("..."); } mTweetEditor.startEditing(message.toString(), 0); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_DESTROY_STATUS: sendCommand(new CommandData(CommandEnum.DESTROY_STATUS, mCurrentId)); return true; case CONTEXT_MENU_ITEM_FAVORITE: sendCommand(new CommandData(CommandEnum.CREATE_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_DESTROY_FAVORITE: sendCommand(new CommandData(CommandEnum.DESTROY_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_SHARE: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder subject = new StringBuilder(); StringBuilder text = new StringBuilder(); String message = c.getString(c.getColumnIndex(Tweets.MESSAGE)); subject.append(getText(R.string.button_create_tweet)); subject.append(" - " + message); int maxlength = 80; if (subject.length() > maxlength) { subject.setLength(maxlength); // Truncate at the last space subject.setLength(subject.lastIndexOf(" ")); subject.append("..."); } text.append(message); text.append("\n-- \n" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID))); text.append("\n URL: " + "http://twitter.com/" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + "/status/" + c.getString(c.getColumnIndex(Tweets._ID))); Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); share.putExtra(Intent.EXTRA_TEXT, text.toString()); startActivity(Intent.createChooser(share, getText(R.string.menu_item_share))); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_UNFOLLOW: case CONTEXT_MENU_ITEM_BLOCK: case CONTEXT_MENU_ITEM_DIRECT_MESSAGE: case CONTEXT_MENU_ITEM_PROFILE: Toast.makeText(this, R.string.unimplemented, Toast.LENGTH_SHORT).show(); return true; } return false; }
From source file:com.wildplot.android.ankistats.ReviewCount.java
public boolean calculateDone(int type, boolean reps) { mType = type;/*from w w w . ja v a 2 s .c o m*/ mBackwards = true; if (reps) { mTitle = R.string.stats_review_count; mAxisTitles = new int[] { type, R.string.stats_answers, R.string.stats_cumulative_answers }; } else { mTitle = R.string.stats_review_time; } mValueLabels = new int[] { R.string.statistics_learn, R.string.statistics_relearn, R.string.statistics_young, R.string.statistics_mature, R.string.statistics_cram }; mColors = new int[] { R.color.stats_learn, R.color.stats_relearn, R.color.stats_young, R.color.stats_mature, R.color.stats_cram }; int num = 0; int chunk = 0; switch (type) { case Utils.TYPE_MONTH: num = 31; chunk = 1; break; case Utils.TYPE_YEAR: num = 52; chunk = 7; break; case Utils.TYPE_LIFE: num = -1; chunk = 30; break; } ArrayList<String> lims = new ArrayList<String>(); if (num != -1) { lims.add("id > " + ((mCollectionData.getDayCutoff() - ((num + 1) * chunk * 86400)) * 1000)); } String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lims.add(lim); } if (lims.size() > 0) { lim = "WHERE "; while (lims.size() > 1) { lim += lims.remove(0) + " AND "; } lim += lims.remove(0); } else { lim = ""; } String ti; String tf; if (!reps) { ti = "time/1000"; if (mType == 0) { tf = "/60.0"; // minutes mAxisTitles = new int[] { type, R.string.stats_minutes, R.string.stats_cumulative_time_minutes }; } else { tf = "/3600.0"; // hours mAxisTitles = new int[] { type, R.string.stats_hours, R.string.stats_cumulative_time_hours }; } } else { ti = "1"; tf = ""; } ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "SELECT (cast((id/1000 - " + mCollectionData.getDayCutoff() + ") / 86400.0 AS INT))/" + chunk + " AS day, " + "sum(CASE WHEN type = 0 THEN " + ti + " ELSE 0 END)" + tf + ", " // lrn + "sum(CASE WHEN type = 1 AND lastIvl < 21 THEN " + ti + " ELSE 0 END)" + tf + ", " // yng + "sum(CASE WHEN type = 1 AND lastIvl >= 21 THEN " + ti + " ELSE 0 END)" + tf + ", " // mtr + "sum(CASE WHEN type = 2 THEN " + ti + " ELSE 0 END)" + tf + ", " // lapse + "sum(CASE WHEN type = 3 THEN " + ti + " ELSE 0 END)" + tf // cram + " FROM revlog " + lim + " GROUP BY day ORDER BY day"; Log.d(AnkiStatsApplication.TAG, "ReviewCount query: " + query); try { cur = mAnkiDb.getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(4), cur.getDouble(2), cur.getDouble(3), cur.getDouble(5) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // small adjustment for a proper chartbuilding with achartengine if (type != Utils.TYPE_LIFE && (list.size() == 0 || list.get(0)[0] > -num)) { list.add(0, new double[] { -num, 0, 0, 0, 0, 0 }); } else if (type == Utils.TYPE_LIFE && list.size() == 0) { list.add(0, new double[] { -12, 0, 0, 0, 0, 0 }); } if (list.get(list.size() - 1)[0] < 0) { list.add(new double[] { 0, 0, 0, 0, 0, 0 }); } mSeriesList = new double[6][list.size()]; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); mSeriesList[0][i] = data[0]; // day mSeriesList[1][i] = data[1] + data[2] + data[3] + data[4] + data[5]; // lrn mSeriesList[2][i] = data[2] + data[3] + data[4] + data[5]; // relearn mSeriesList[3][i] = data[3] + data[4] + data[5]; // young mSeriesList[4][i] = data[4] + data[5]; // mature mSeriesList[5][i] = data[5]; // cram if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) Math.round(data[1] + data[2] + data[3] + data[4] + data[5]); if (data[5] >= 0.999) mFoundCramCards = true; if (data[1] >= 0.999) mFoundLearnCards = true; if (data[2] >= 0.999) mFoundRelearnCards = true; if (data[0] > mLastElement) mLastElement = data[0]; if (data[0] < mFirstElement) mFirstElement = data[0]; if (data[0] == 0) { mZeroIndex = i; } } mMaxElements = list.size() - 1; return list.size() > 0; }
From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java
/** * Deletions ******************************************************************** *//*from ww w . j a va 2 s . c om*/ private JSONObject removed() { JSONArray cards = new JSONArray(); JSONArray notes = new JSONArray(); JSONArray decks = new JSONArray(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery( "SELECT oid, type FROM graves WHERE usn" + (mCol.getServer() ? (" >= " + mMinUsn) : (" = -1")), null); while (cur.moveToNext()) { int type = cur.getInt(1); switch (type) { case Sched.REM_CARD: cards.put(cur.getLong(0)); break; case Sched.REM_NOTE: notes.put(cur.getLong(0)); break; case Sched.REM_DECK: decks.put(cur.getLong(0)); break; } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mCol.getServer()) { mCol.getDb().execute("UPDATE graves SET usn=" + mMaxUsn + " WHERE usn=-1"); } JSONObject o = new JSONObject(); try { o.put("cards", cards); o.put("notes", notes); o.put("decks", decks); } catch (JSONException e) { throw new RuntimeException(e); } return o; }
From source file:com.ichi2.libanki.sync.Syncer.java
/** * Deletions ******************************************************************** *//* w ww. ja va2 s. co m*/ private JSONObject removed() { JSONArray cards = new JSONArray(); JSONArray notes = new JSONArray(); JSONArray decks = new JSONArray(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery( "SELECT oid, type FROM graves WHERE usn" + (mCol.getServer() ? (" >= " + mMinUsn) : (" = -1")), null); while (cur.moveToNext()) { int type = cur.getInt(1); switch (type) { case Consts.REM_CARD: cards.put(cur.getLong(0)); break; case Consts.REM_NOTE: notes.put(cur.getLong(0)); break; case Consts.REM_DECK: decks.put(cur.getLong(0)); break; } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mCol.getServer()) { mCol.getDb().execute("UPDATE graves SET usn=" + mMaxUsn + " WHERE usn=-1"); } JSONObject o = new JSONObject(); try { o.put("cards", cards); o.put("notes", notes); o.put("decks", decks); } catch (JSONException e) { throw new RuntimeException(e); } return o; }
From source file:com.ichi2.libanki.Stats.java
/** * Intervals *********************************************************************************************** */// ww w .j a v a 2 s. com public boolean calculateIntervals(Context context, int type) { mDynamicAxis = true; mType = type; double all = 0, avg = 0, max_ = 0; mBackwards = false; mTitle = R.string.stats_review_intervals; mAxisTitles = new int[] { type, R.string.stats_cards, R.string.stats_percentage }; mValueLabels = new int[] { R.string.stats_cards_intervals }; mColors = new int[] { R.color.stats_interval }; int num = 0; String lim = ""; int chunk = 0; switch (type) { case TYPE_MONTH: num = 31; chunk = 1; lim = " and grp <= 30"; break; case TYPE_YEAR: num = 52; chunk = 7; lim = " and grp <= 52"; break; case TYPE_LIFE: num = -1; chunk = 30; lim = ""; break; } ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery("select ivl / " + chunk + " as grp, count() from cards " + "where did in " + _limit() + " and queue = 2 " + lim + " " + "group by grp " + "order by grp", null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1) }); } if (cur != null && !cur.isClosed()) { cur.close(); } cur = mCol.getDb().getDatabase().rawQuery( "select count(), avg(ivl), max(ivl) from cards where did in " + _limit() + " and queue = 2", null); cur.moveToFirst(); all = cur.getDouble(0); avg = cur.getDouble(1); max_ = cur.getDouble(2); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // small adjustment for a proper chartbuilding with achartengine if (list.size() == 0 || list.get(0)[0] > 0) { list.add(0, new double[] { 0, 0, 0 }); } if (num == -1 && list.size() < 2) { num = 31; } if (type != TYPE_LIFE && list.get(list.size() - 1)[0] < num) { list.add(new double[] { num, 0 }); } else if (type == TYPE_LIFE && list.size() < 2) { list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0 }); } mLastElement = 0; mSeriesList = new double[2][list.size()]; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); mSeriesList[0][i] = data[0]; // grp mSeriesList[1][i] = data[1]; // cnt if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) Math.round(data[1]); if (data[0] > mLastElement) mLastElement = data[0]; } mCumulative = createCumulative(mSeriesList); for (int i = 0; i < list.size(); i++) { mCumulative[1][i] /= all / 100; } mMcount = 100; switch (mType) { case TYPE_MONTH: mLastElement = 31; break; case TYPE_YEAR: mLastElement = 52; break; default: } mFirstElement = 0; mMaxElements = list.size() - 1; mAverage = Utils.timeSpan(context, (int) Math.round(avg * 86400)); mLongest = Utils.timeSpan(context, (int) Math.round(max_ * 86400)); //some adjustments to not crash the chartbuilding with emtpy data if (mMaxElements == 0) { mMaxElements = 10; } if (mMcount == 0) { mMcount = 10; } if (mFirstElement == mLastElement) { mFirstElement = 0; mLastElement = 6; } if (mMaxCards == 0) mMaxCards = 10; return list.size() > 0; }
From source file:com.stfalcon.contentmanager.ContentManager.java
private Uri getFileUriFromContentUri(Uri cameraPicUri) { Cursor cursor = null; try {/*from w w w. j a v a2 s. co m*/ if (cameraPicUri != null && cameraPicUri.toString().startsWith("content")) { String[] proj = { MediaStore.Images.Media.DATA }; cursor = activity.getContentResolver().query(cameraPicUri, proj, null, null, null); cursor.moveToFirst(); // This will actually give you the file path location of the image. String largeImagePath = cursor .getString(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); return Uri.fromFile(new File(largeImagePath)); } return cameraPicUri; } catch (Exception e) { return cameraPicUri; } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } }
From source file:org.opendatakit.tables.utils.CollectUtil.java
private static boolean isExistingCollectInstanceForRowData(Context context, String appName, String tableId, String rowId) {//from ww w. j av a 2s . c o m Cursor c = null; try { String instanceFilePath = getEditRowFormFile(appName, tableId, rowId).getAbsolutePath(); c = context.getContentResolver().query(CONTENT_INSTANCE_URI, null, COLLECT_KEY_INSTANCE_FILE_PATH + "=?", new String[] { instanceFilePath }, COLLECT_INSTANCE_ORDER_BY); if (c.getCount() == 0) { c.close(); return false; } c.close(); return true; } catch (Exception e) { WebLogger.getLogger(appName).w(TAG, "caught an exception while deleting an instance, " + "ignoring and proceeding"); return true; // since we don't really know what is going on... } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. *//*from ww w .ja v a 2 s . co m*/ private long addLocation(String locationSetting, String cityName, double lat, double lon) { ContentResolver locationResolver = getContext().getContentResolver(); Cursor locationCursor = locationResolver.query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); long locationId; // Students: First, check if the location with this city name exists in the db if (locationCursor != null && locationCursor.moveToFirst()) { // If it exists, return the current ID locationId = locationCursor.getLong(locationCursor.getColumnIndex(LocationEntry._ID)); } else { // Otherwise, insert it using the content resolver and the base URI ContentValues locationValues = new ContentValues(); locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon); Uri insertUri = locationResolver.insert(LocationEntry.CONTENT_URI, locationValues); locationId = ContentUris.parseId(insertUri); } if (locationCursor != null && !locationCursor.isClosed()) { locationCursor.close(); } return locationId; }
From source file:org.opendatakit.tables.utils.CollectUtil.java
/** * Return the Collect form values from the given instance id. * * @param context/* w w w.j a v a 2 s . c om*/ * @param instanceId * @return */ public static FormValues getOdkCollectFormValuesFromInstanceId(Context context, String appName, int instanceId) { String[] projection = { COLLECT_KEY_LAST_STATUS_CHANGE_DATE, "displayName", "instanceFilePath" }; String selection = "_id = ?"; String[] selectionArgs = { (instanceId + "") }; Cursor c = null; try { c = context.getContentResolver().query(COLLECT_INSTANCES_CONTENT_URI, projection, selection, selectionArgs, null); if (c.getCount() != 1) { return null; } c.moveToFirst(); FormValues fv = new FormValues(); fv.timestamp = ODKDatabaseUtils.get().getIndexAsType(c, Long.class, c.getColumnIndexOrThrow(COLLECT_KEY_LAST_STATUS_CHANGE_DATE)); String instancepath = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndexOrThrow("instanceFilePath")); File instanceFile = new File(instancepath); parseXML(appName, fv, instanceFile); return fv; } finally { if (c != null && !c.isClosed()) { c.close(); } } }