List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:com.hichinaschool.flashcards.libanki.Stats.java
/** * Due and cumulative due/* w w w . ja v a 2 s . c o m*/ * *********************************************************************************************** */ public boolean calculateDue(int type) { mType = type; mBackwards = false; mTitle = R.string.stats_forecast; mValueLabels = new int[] { R.string.statistics_young, R.string.statistics_mature }; mColors = new int[] { R.color.stats_young, R.color.stats_mature }; mAxisTitles = new int[] { type, R.string.stats_cards }; int end = 0; int chunk = 0; switch (type) { case TYPE_MONTH: end = 31; chunk = 1; break; case TYPE_YEAR: end = 52; chunk = 7; break; case TYPE_LIFE: end = -1; chunk = 30; break; } String lim = "";// AND due - " + mCol.getSched().getToday() + " >= " + start; // leave this out in order to show // card too which were due the days before if (end != -1) { lim += " AND day <= " + end; } ArrayList<int[]> dues = new ArrayList<int[]>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase() .rawQuery("SELECT (due - " + mCol.getSched().getToday() + ")/" + chunk + " AS day, " // day + "count(), " // all cards + "sum(CASE WHEN ivl >= 21 THEN 1 ELSE 0 END) " // mature cards + "FROM cards WHERE did IN " + _limit() + " AND queue IN (2,3)" + lim + " GROUP BY day ORDER BY day", null); while (cur.moveToNext()) { dues.add(new int[] { cur.getInt(0), cur.getInt(1), cur.getInt(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // small adjustment for a proper chartbuilding with achartengine if (dues.size() == 0 || dues.get(0)[0] > 0) { dues.add(0, new int[] { 0, 0, 0 }); } if (end == -1 && dues.size() < 2) { end = 31; } if (type != TYPE_LIFE && dues.get(dues.size() - 1)[0] < end) { dues.add(new int[] { end, 0, 0 }); } else if (type == TYPE_LIFE && dues.size() < 2) { dues.add(new int[] { Math.max(12, dues.get(dues.size() - 1)[0] + 1), 0, 0 }); } mSeriesList = new double[3][dues.size()]; for (int i = 0; i < dues.size(); i++) { int[] data = dues.get(i); mSeriesList[0][i] = data[0]; mSeriesList[1][i] = data[1]; mSeriesList[2][i] = data[2]; } return dues.size() > 0; }
From source file:de.ub0r.android.websms.WebSMSReceiver.java
/** * Save Message to internal database.//from w w w .j a v a 2s .c om * * @param context {@link android.content.Context} * @param specs {@link de.ub0r.android.websms.connector.common.ConnectorSpec} * @param command {@link de.ub0r.android.websms.connector.common.ConnectorCommand} * @param msgType sent or draft? */ static void saveMessage(final Context context, final ConnectorSpec specs, final ConnectorCommand command, final int msgType) { if (command.getType() != ConnectorCommand.TYPE_SEND) { return; } if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(WebSMS.PREFS_DROP_SENT, false)) { Log.i(TAG, "drop sent messages"); return; } // save message to android's internal sms database final ContentResolver cr = context.getContentResolver(); assert cr != null; final ContentValues values = new ContentValues(); values.put(TYPE, msgType); if (msgType == MESSAGE_TYPE_SENT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (isRealSMS(specs)) { // drop messages from "SMS" connector. it gets saved internally. return; } try { // API19+ does not allow writing to content://sms anymore // anyway, give it a try, if SMSdroid is not installed // AppOps might let the app write the message if (Telephony.Sms.getDefaultSmsPackage(context).equals("de.ub0r.android.smsdroid")) { sendMessageToSMSdroid(context, specs, command); return; } } catch (NullPointerException e) { Log.w(TAG, "there is no telephony service!"); // fall back saving the message the old fashion way. it might work.. } } final String[] uris = command.getMsgUris(); if (uris != null && uris.length > 0) { for (String s : uris) { final Uri u = Uri.parse(s); try { final int updated = cr.update(u, values, null, null); Log.d(TAG, "updated: " + updated); if (updated > 0 && specs != null && !isRealSMS(specs)) { sendMessageToCallMeter(context, specs, u); } } catch (SQLiteException e) { Log.e(TAG, "error updating sent message: " + u, e); Toast.makeText(context, R.string.log_error_saving_message, Toast.LENGTH_LONG).show(); } } return; // skip legacy saving } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { return; // skip saving drafts on API19+ } final String text = command.getText(); Log.d(TAG, "save message(s):"); Log.d(TAG, "type: " + msgType); Log.d(TAG, "TEXT: " + text); values.put(READ, 1); values.put(BODY, text); if (command.getSendLater() > 0) { values.put(DATE, command.getSendLater()); Log.d(TAG, "DATE: " + command.getSendLater()); } final String[] recipients = command.getRecipients(); final ArrayList<String> inserted = new ArrayList<String>(recipients.length); for (String recipient : recipients) { if (recipient == null || recipient.trim().length() == 0) { continue; // skip empty recipients } String address = Utils.getRecipientsNumber(recipient); Log.d(TAG, "TO: " + address); try { final Cursor c = cr.query( URI_SMS, PROJECTION_ID, TYPE + " = " + MESSAGE_TYPE_DRAFT + " AND " + ADDRESS + " = '" + address + "' AND " + BODY + " like '" + text.replace("'", "_") + "'", null, DATE + " DESC"); if (c != null && c.moveToFirst()) { final Uri u = URI_SENT.buildUpon().appendPath(c.getString(0)).build(); assert u != null; Log.d(TAG, "skip saving draft: " + u); inserted.add(u.toString()); } else { final ContentValues cv = new ContentValues(values); cv.put(ADDRESS, address); // save sms to content://sms/sent Uri u = cr.insert(URI_SENT, cv); if (u != null) { inserted.add(u.toString()); if (msgType == MESSAGE_TYPE_SENT) { // API19+ code may reach this point // SMSdroid is not default app // but message was saved as sent somehow sendMessageToCallMeter(context, specs, u); } } } if (c != null && !c.isClosed()) { c.close(); } } catch (SQLiteException e) { Log.e(TAG, "failed saving message", e); } catch (IllegalArgumentException e) { Log.e(TAG, "failed saving message", e); Toast.makeText(context, R.string.log_error_saving_message, Toast.LENGTH_LONG).show(); } } if (msgType == MESSAGE_TYPE_DRAFT && inserted.size() > 0) { command.setMsgUris(inserted.toArray(new String[inserted.size()])); } }
From source file:com.chatwing.whitelabel.services.NotificationIntentService.java
private List<Message> getMessagesByGroup(String conversationId) { Cursor cursor = null; try {//from w ww . ja va 2s . c o m cursor = getContentResolver().query(ChatWingContentProvider.getNotificationMessagesUri(), NotificationMessagesTable.getMinimumProjection(), NotificationMessagesTable.CONVERSATION_ID + " ==\"" + conversationId + "\"", null, NotificationMessagesTable.CREATED_DATE + " DESC"); boolean hasNext = cursor.moveToFirst(); List<Message> messages = new ArrayList<Message>(); while (hasNext) { Message message = NotificationMessagesTable.getMessage(cursor); if (message != null) { messages.add(message); } hasNext = cursor.moveToNext(); } return messages; } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } }
From source file:com.wildplot.android.ankistats.AnswerButton.java
public boolean calculateAnswerButtons(int type) { mTitle = R.string.stats_answer_buttons; mAxisTitles = new int[] { R.string.stats_answer_type, R.string.stats_answers, R.string.stats_cumulative_correct_percentage }; mValueLabels = new int[] { R.string.statistics_learn, R.string.statistics_young, R.string.statistics_mature }; mColors = new int[] { R.color.stats_learn, R.color.stats_young, R.color.stats_mature }; mType = type;/*from ww w. j a v a 2 s . c om*/ String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", ""); String lims = ""; //TODO when non whole collection selection is possible test this! int days = 0; if (lim.length() > 0) lims += lim + " and "; if (type == Utils.TYPE_MONTH) days = 30; else if (type == Utils.TYPE_YEAR) days = 365; else days = -1; if (days > 0) lims += "id > " + ((mCollectionData.getDayCutoff() - (days * 86400)) * 1000); if (lims.length() > 0) lim = "where " + lims; else lim = ""; ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "select (case " + " when type in (0,2) then 0 " + " when lastIvl < 21 then 1 " + " else 2 end) as thetype, " + " (case when type in (0,2) and ease = 4 then 3 else ease end), count() from revlog " + lim + " " + " group by thetype, ease " + " order by thetype, ease"; try { cur = mAnkiDb.getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } //TODO adjust for AnswerButton, for now only copied from intervals // 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 != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) { // list.add(new double[] { num, 0, 0 }); // } else if (type == Utils.TYPE_LIFE && list.size() < 2) { // list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 }); // } double[] totals = new double[3]; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int currentType = (int) data[0]; double ease = data[1]; double cnt = data[2]; totals[currentType] += cnt; } int badNew = 0; int badYoung = 0; int badMature = 0; mSeriesList = new double[4][list.size() + 1]; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int currentType = (int) data[0]; double ease = data[1]; double cnt = data[2]; if (currentType == 1) ease += 5; else if (currentType == 2) ease += 10; if ((int) ease == 1) { badNew = i; } if ((int) ease == 6) { badYoung = i; } if ((int) ease == 11) { badMature = i; } mSeriesList[0][i] = ease; mSeriesList[1 + currentType][i] = cnt; if (cnt > mMaxCards) mMaxCards = (int) cnt; } mSeriesList[0][list.size()] = 15; mCumulative = new double[4][]; mCumulative[0] = mSeriesList[0]; mCumulative[1] = Utils.createCumulativeInPercent(mSeriesList[1], totals[0], badNew); mCumulative[2] = Utils.createCumulativeInPercent(mSeriesList[2], totals[1], badYoung); mCumulative[3] = Utils.createCumulativeInPercent(mSeriesList[3], totals[2], badMature); mMaxElements = 15; //bars are positioned from 1 to 14 return list.size() > 0; }
From source file:saschpe.birthdays.service.loader.ContactAccountListLoader.java
@Override public List<AccountModel> loadInBackground() { if (!AccountHelper.isAccountActivated(getContext())) { AccountHelper.addAccount(getContext()); }//www .ja va 2 s. c om // Retrieve all accounts that are actively used for contacts HashSet<Account> contactAccounts = new HashSet<>(); Cursor cursor = null; try { cursor = getContext().getContentResolver() .query(ContactsContract.RawContacts.CONTENT_URI, new String[] { ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE }, null, null, null); while (cursor.moveToNext()) { String account_name = cursor .getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)); String account_type = cursor .getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)); Account account = new Account(account_name, account_type); contactAccounts.add(account); } } catch (Exception e) { Log.e(TAG, "Error retrieving accounts", e); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } List<Account> accountBlacklist = AccountProviderHelper.getAccountList(getContext()); Log.d(TAG, "Stored account list: " + accountBlacklist); AccountManager manager = AccountManager.get(getContext()); AuthenticatorDescription[] descriptions = manager.getAuthenticatorTypes(); ArrayList<AccountModel> items = new ArrayList<>(); for (Account account : contactAccounts) { for (AuthenticatorDescription description : descriptions) { if (description.type.equals(account.type)) { boolean disabled = accountBlacklist.contains(account); items.add(new AccountModel(getContext(), account, description, !disabled)); } } } // Sort the list Collections.sort(items, ALPHA_COMPARATOR); return items; }
From source file:com.wildplot.android.ankistats.Forecast.java
/** * Due and cumulative due/* w ww .java 2 s . c o m*/ * *********************************************************************************************** */ private boolean calculateDue(int type) { mType = type; mBackwards = false; mTitle = R.string.stats_forecast; mValueLabels = new int[] { R.string.statistics_young, R.string.statistics_mature }; mColors = new int[] { R.color.stats_young, R.color.stats_mature }; mAxisTitles = new int[] { type, R.string.stats_cards, R.string.stats_cumulative_cards }; int end = 0; int chunk = 0; switch (type) { case Utils.TYPE_MONTH: end = 31; chunk = 1; break; case Utils.TYPE_YEAR: end = 52; chunk = 7; break; case Utils.TYPE_LIFE: end = -1; chunk = 30; break; } String lim = "";// AND due - " + mCol.getSched().getToday() + " >= " + start; // leave this out in order to show // card too which were due the days before if (end != -1) { lim += " AND day <= " + end; } ArrayList<int[]> dues = new ArrayList<int[]>(); Cursor cur = null; try { String query; query = "SELECT (due - " + mCollectionData.getToday() + ")/" + chunk + " AS day, " // day + "count(), " // all cards + "sum(CASE WHEN ivl >= 21 THEN 1 ELSE 0 END) " // mature cards + "FROM cards WHERE did IN " + _limitWholeOnly() + " AND queue IN (2,3)" + lim + " GROUP BY day ORDER BY day"; //TODO remove: System.out.println("forecast query: " + query); cur = mAnkiDb.getDatabase().rawQuery(query, null); while (cur.moveToNext()) { dues.add(new int[] { cur.getInt(0), cur.getInt(1), cur.getInt(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // small adjustment for a proper chartbuilding with achartengine if (dues.size() == 0 || dues.get(0)[0] > 0) { dues.add(0, new int[] { 0, 0, 0 }); } if (end == -1 && dues.size() < 2) { end = 31; } if (type != Utils.TYPE_LIFE && dues.get(dues.size() - 1)[0] < end) { dues.add(new int[] { end, 0, 0 }); } else if (type == Utils.TYPE_LIFE && dues.size() < 2) { dues.add(new int[] { Math.max(12, dues.get(dues.size() - 1)[0] + 1), 0, 0 }); } mSeriesList = new double[3][dues.size()]; for (int i = 0; i < dues.size(); i++) { int[] data = dues.get(i); if (data[1] > mMaxCards) mMaxCards = data[1]; mSeriesList[0][i] = data[0]; mSeriesList[1][i] = data[1]; mSeriesList[2][i] = data[2]; if (data[0] > mLastElement) mLastElement = data[0]; if (data[0] == 0) { mZeroIndex = i; } } mMaxElements = dues.size() - 1; return dues.size() > 0; }
From source file:com.irccloud.android.IRCCloudApplicationBase.java
@Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) TrustKit.initializeWithNetworkSecurityConfiguration(getApplicationContext(), R.xml.network_security_config); Fabric.with(this, new Crashlytics()); Crashlytics.log(Log.INFO, "IRCCloud", "Crashlytics Initialized"); FlowManager.init(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (Build.VERSION.SDK_INT >= 19) EmojiCompat.init(/*from w w w . j av a 2 s . c om*/ new BundledEmojiCompatConfig(this).setReplaceAll(!prefs.getBoolean("preferSystemEmoji", true))); /*EmojiCompat.init(new FontRequestEmojiCompatConfig(getApplicationContext(), new FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", "Noto Color Emoji Compat", R.array.com_google_android_gms_fonts_certs)) .setReplaceAll(!prefs.getBoolean("preferSystemEmoji", true)) .registerInitCallback(new EmojiCompat.InitCallback() { @Override public void onInitialized() { super.onInitialized(); EventsList.getInstance().clearCaches(); conn.notifyHandlers(NetworkConnection.EVENT_FONT_DOWNLOADED, null); } }));*/ NetworkConnection.getInstance().registerForConnectivity(); //Disable HTTP keep-alive for our app, as some versions of Android will return an empty response System.setProperty("http.keepAlive", "false"); //Allocate all the shared objects at launch conn = NetworkConnection.getInstance(); ColorFormatter.init(); if (prefs.contains("notify")) { SharedPreferences.Editor editor = prefs.edit(); editor.putString("notify_type", prefs.getBoolean("notify", true) ? "1" : "0"); editor.remove("notify"); editor.commit(); } if (prefs.contains("notify_sound")) { SharedPreferences.Editor editor = prefs.edit(); if (!prefs.getBoolean("notify_sound", true)) editor.putString("notify_ringtone", ""); editor.remove("notify_sound"); editor.commit(); } if (prefs.contains("notify_lights")) { SharedPreferences.Editor editor = prefs.edit(); if (!prefs.getBoolean("notify_lights", true)) editor.putString("notify_led_color", "0"); editor.remove("notify_lights"); editor.commit(); } if (!prefs.getBoolean("ringtone_migrated", false)) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { String notification_uri = prefs.getString("notify_ringtone", ""); if (notification_uri.startsWith("content://media/external/audio/media/")) { Cursor c = getContentResolver().query(Uri.parse(notification_uri), new String[] { MediaStore.Audio.Media.TITLE }, null, null, null); if (c != null && c.moveToFirst()) { if (c.getString(0).equals("IRCCloud")) { Log.d("IRCCloud", "Migrating notification ringtone setting: " + notification_uri); SharedPreferences.Editor editor = prefs.edit(); editor.remove("notify_ringtone"); editor.commit(); } } if (c != null && !c.isClosed()) { c.close(); } } File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS); File file = new File(path, "IRCCloud.mp3"); if (file.exists()) { file.delete(); } try { getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media.TITLE + " = 'IRCCloud'", null); } catch (Exception e) { // Ringtone not in media DB } } try { String notification_uri = prefs.getString("notify_ringtone", ""); if (notification_uri.startsWith("content://media/")) { Cursor c = getContentResolver().query(Uri.parse(notification_uri), new String[] { MediaStore.Audio.Media.TITLE }, null, null, null); if (c != null && c.moveToFirst()) { if (c.getString(0).equals("IRCCloud")) { Log.d("IRCCloud", "Migrating notification ringtone setting: " + notification_uri); SharedPreferences.Editor editor = prefs.edit(); editor.remove("notify_ringtone"); editor.commit(); } } if (c != null && !c.isClosed()) { c.close(); } } } catch (Exception e) { //We might not have permission to query the media DB } try { getContentResolver().delete(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MediaStore.Audio.Media.TITLE + " = 'IRCCloud'", null); } catch (Exception e) { // Ringtone not in media DB e.printStackTrace(); } File file = new File(getFilesDir(), "IRCCloud.mp3"); if (file.exists()) { file.delete(); } SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("ringtone_migrated", true); editor.commit(); } if (prefs.contains("notify_pebble")) { try { int pebbleVersion = getPackageManager().getPackageInfo("com.getpebble.android", 0).versionCode; if (pebbleVersion >= 553 && Build.VERSION.SDK_INT >= 18) { SharedPreferences.Editor editor = prefs.edit(); editor.remove("notify_pebble"); editor.commit(); } } catch (Exception e) { } } if (prefs.contains("acra.enable")) { SharedPreferences.Editor editor = prefs.edit(); editor.remove("acra.enable"); editor.commit(); } if (prefs.contains("notifications_json")) { SharedPreferences.Editor editor = prefs.edit(); editor.remove("notifications_json"); editor.remove("networks_json"); editor.remove("lastseeneids_json"); editor.remove("dismissedeids_json"); editor.commit(); } prefs = getSharedPreferences("prefs", 0); if (prefs.getString("host", "www.irccloud.com").equals("www.irccloud.com") && !prefs.contains("path") && prefs.contains("session_key")) { Crashlytics.log(Log.INFO, "IRCCloud", "Migrating path from session key"); SharedPreferences.Editor editor = prefs.edit(); editor.putString("path", "/websocket/" + prefs.getString("session_key", "").charAt(0)); editor.commit(); } if (prefs.contains("host") && prefs.getString("host", "").equals("www.irccloud.com")) { Crashlytics.log(Log.INFO, "IRCCloud", "Migrating host"); SharedPreferences.Editor editor = prefs.edit(); editor.putString("host", "api.irccloud.com"); editor.commit(); } if (prefs.contains("gcm_app_version")) { SharedPreferences.Editor editor = prefs.edit(); editor.remove("gcm_app_version"); editor.remove("gcm_app_build"); editor.remove("gcm_registered"); editor.remove("gcm_reg_id"); editor.commit(); } NetworkConnection.IRCCLOUD_HOST = prefs.getString("host", BuildConfig.HOST); NetworkConnection.IRCCLOUD_PATH = prefs.getString("path", "/"); /*try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) WebView.setWebContentsDebuggingEnabled(true); } } catch (Exception e) { }*/ /*FontRequest request = new FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", "Dekko", R.array.com_google_android_gms_fonts_certs); FontsContractCompat.requestFont(getApplicationContext(), request, new FontsContractCompat.FontRequestCallback() { @Override public void onTypefaceRetrieved(Typeface typeface) { csFont = typeface; EventsList.getInstance().clearCaches(); NetworkConnection.getInstance().notifyHandlers(NetworkConnection.EVENT_FONT_DOWNLOADED, null); } }, getFontsHandler());*/ Crashlytics.log(Log.INFO, "IRCCloud", "App Initialized"); }
From source file:com.wildplot.android.ankistats.WeeklyBreakdown.java
public boolean calculateBreakdown(int type) { mTitle = R.string.stats_weekly_breakdown; mAxisTitles = new int[] { R.string.stats_day_of_week, R.string.stats_percentage_correct, R.string.stats_reviews };/*from ww w .ja v a 2 s . co m*/ mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers }; mColors = new int[] { R.color.stats_counts, R.color.stats_hours }; mType = type; String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lim = " and " + lim; } Calendar sd = GregorianCalendar.getInstance(); sd.setTimeInMillis(mCollectionData.getDayCutoff() * 1000); int pd = _periodDays(); if (pd > 0) { lim += " and id > " + ((mCollectionData.getDayCutoff() - (86400 * pd)) * 1000); } long cutoff = mCollectionData.getDayCutoff(); long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600; ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "SELECT strftime('%w',datetime( cast(id/ 1000 -" + sd.get(Calendar.HOUR_OF_DAY) * 3600 + " as int), 'unixepoch')) as wd, " + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() " + "from revlog " + "where type in (0,1,2) " + lim + " " + "group by wd " + "order by wd"; Log.d(AnkiStatsApplication.TAG, sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " weekly breakdown query: " + query); try { cur = mAnkiDb.getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } //TODO adjust for breakdown, for now only copied from intervals // 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 != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) { // list.add(new double[] { num, 0, 0 }); // } else if (type == Utils.TYPE_LIFE && list.size() < 2) { // list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 }); // } mSeriesList = new double[4][list.size()]; mPeak = 0.0; mMcount = 0.0; double minHour = Double.MAX_VALUE; double maxHour = 0; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int hour = (int) data[0]; //double hour = data[0]; if (hour < minHour) minHour = hour; if (hour > maxHour) maxHour = hour; double pct = data[1]; if (pct > mPeak) mPeak = pct; mSeriesList[0][i] = hour; mSeriesList[1][i] = pct; mSeriesList[2][i] = data[2]; if (i == 0) { mSeriesList[3][i] = pct; } else { double prev = mSeriesList[3][i - 1]; double diff = pct - prev; diff /= 3.0; diff = Math.round(diff * 10.0) / 10.0; mSeriesList[3][i] = prev + diff; } if (data[2] > mMcount) mMcount = data[2]; if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) mSeriesList[1][i]; } mMaxElements = (int) (maxHour - minHour); return list.size() > 0; }
From source file:com.chatwingsdk.managers.CommunicationModeManager.java
private void subscribeToChatBoxChannels(WebView mWebView) { // Query for chat box keys Uri chatBoxesUri = ChatWingContentProvider.getChatBoxesUri(); ArrayList<String> fayeChannels = new ArrayList<String>(); Cursor c = null; try {//from w w w . j a v a2 s . com c = mActivityDelegate.getActivity().getContentResolver().query(chatBoxesUri, new String[] { ChatBoxTable.FAYE_CHANNEL }, null, null, null); if (c.getCount() > 0 && c.moveToFirst()) { int fayeChannelIndex = c.getColumnIndex(ChatBoxTable.FAYE_CHANNEL); do { // We can subscribe to each chat box here, // but it can take a lot of time and holding the Cursor for // that long is not a good idea. So, to be safe, // let's get all chat box keys first and subscribe later. String fayeChannel = c.getString(fayeChannelIndex); fayeChannels.add(fayeChannel); } while (c.moveToNext()); } } finally { if (c != null && !c.isClosed()) { c.close(); } } // Subscribe to all of them for (String fayeChannel : fayeChannels) { String js = String.format("javascript:subscribe('%s')", fayeChannel); mWebView.loadUrl(js); } }
From source file:com.wildplot.android.ankistats.HourlyBreakdown.java
public boolean calculateBreakdown(int type) { mTitle = R.string.stats_breakdown;/*from w ww.j a va 2 s .com*/ mAxisTitles = new int[] { R.string.stats_time_of_day, R.string.stats_percentage_correct, R.string.stats_reviews }; mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers }; mColors = new int[] { R.color.stats_counts, R.color.stats_hours }; mType = type; String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lim = " and " + lim; } Calendar sd = GregorianCalendar.getInstance(); sd.setTimeInMillis(mCollectionData.getCrt() * 1000); Calendar cal = Calendar.getInstance(); TimeZone tz = TimeZone.getDefault(); /* date formatter in local timezone */ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); sdf.setTimeZone(tz); /* print your timestamp and double check it's the date you expect */ String localTime = sdf.format(new Date(mCollectionData.getCrt() * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds? int pd = _periodDays(); if (pd > 0) { lim += " and id > " + ((mCollectionData.getDayCutoff() - (86400 * pd)) * 1000); } int hourOfDay = sd.get(GregorianCalendar.HOUR_OF_DAY); long cutoff = mCollectionData.getDayCutoff(); long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600; ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "select " + "23 - ((cast((" + cut + " - id/1000) / 3600.0 as int)) % 24) as hour, " + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() " + "from revlog where type in (0,1,2) " + lim + " " + "group by hour having count() > 30 order by hour"; Log.d(AnkiStatsApplication.TAG, sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " breakdown query: " + query); try { cur = mAnkiDb.getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } //TODO adjust for breakdown, for now only copied from intervals // 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 != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) { // list.add(new double[] { num, 0, 0 }); // } else if (type == Utils.TYPE_LIFE && list.size() < 2) { // list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 }); // } for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int intHour = (int) data[0]; int hour = (intHour - 4) % 24; if (hour < 0) hour += 24; data[0] = hour; list.set(i, data); } Collections.sort(list, new Comparator<double[]>() { @Override public int compare(double[] s1, double[] s2) { if (s1[0] < s2[0]) return -1; if (s1[0] > s2[0]) return 1; return 0; } }); mSeriesList = new double[4][list.size()]; mPeak = 0.0; mMcount = 0.0; double minHour = Double.MAX_VALUE; double maxHour = 0; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int hour = (int) data[0]; //double hour = data[0]; if (hour < minHour) minHour = hour; if (hour > maxHour) maxHour = hour; double pct = data[1]; if (pct > mPeak) mPeak = pct; mSeriesList[0][i] = hour; mSeriesList[1][i] = pct; mSeriesList[2][i] = data[2]; if (i == 0) { mSeriesList[3][i] = pct; } else { double prev = mSeriesList[3][i - 1]; double diff = pct - prev; diff /= 3.0; diff = Math.round(diff * 10.0) / 10.0; mSeriesList[3][i] = prev + diff; } if (data[2] > mMcount) mMcount = data[2]; if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) mSeriesList[1][i]; } mMaxElements = (int) (maxHour - minHour); return list.size() > 0; }