List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:group.pals.android.lib.ui.filechooser.FragmentFiles.java
/** * Creates new {@link #mFileSelector} to select appropriate file after * loading a folder's content. It's either the parent path of last path, or * the file provided by key {@link FileChooserActivity#EXTRA_SELECT_FILE}. * Note that this also cancels previous selector if there is such one. *//*from w ww .j av a 2 s.c om*/ private void createFileSelector() { if (mFileSelector != null) mFileSelector.cancel(true); mFileSelector = new LoadingDialog<Void, Void, Integer>(getActivity(), true) { @Override protected Integer doInBackground(Void... params) { final Cursor cursor = mFileAdapter.getCursor(); if (cursor == null || cursor.isClosed()) return -1; final Uri selectedFile = (Uri) getArguments().getParcelable(FileChooserActivity.EXTRA_SELECT_FILE); final int colUri = cursor.getColumnIndex(BaseFile.COLUMN_URI); if (selectedFile != null) getArguments().remove(FileChooserActivity.EXTRA_SELECT_FILE); int shouldBeSelectedIdx = -1; final Uri uri = selectedFile != null ? selectedFile : getLastLocation(); if (uri == null || !BaseFileProviderUtils.fileExists(getActivity(), uri)) return -1; final String fileName = BaseFileProviderUtils.getFileName(getActivity(), uri); if (fileName == null) return -1; Uri parentUri = BaseFileProviderUtils.getParentFile(getActivity(), uri); if ((uri == getLastLocation() && !getCurrentLocation().equals(getLastLocation()) && BaseFileProviderUtils.isAncestorOf(getActivity(), getCurrentLocation(), uri)) || getCurrentLocation().equals(parentUri)) { if (cursor.moveToFirst()) { while (!cursor.isLast()) { if (isCancelled()) return -1; Uri subUri = Uri.parse(cursor.getString(colUri)); if (uri == getLastLocation()) { if (cursor.getInt(cursor .getColumnIndex(BaseFile.COLUMN_TYPE)) == BaseFile.FILE_TYPE_DIRECTORY) { if (subUri.equals(uri) || BaseFileProviderUtils.isAncestorOf(getActivity(), subUri, uri)) { shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2); break; } } } else { if (uri.equals(subUri)) { shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2); break; } } cursor.moveToNext(); } // while } // if } // if return shouldBeSelectedIdx; }// doInBackground() @Override protected void onPostExecute(final Integer result) { super.onPostExecute(result); if (isCancelled() || mFileAdapter.isEmpty()) return; /* * Use a Runnable to make sure this works. Because if the list * view is handling data, this might not work. * * Also sometimes it doesn't work without a delay. */ mViewFiles.postDelayed(new Runnable() { @Override public void run() { if (result >= 0 && result < mFileAdapter.getCount()) mViewFiles.setSelection(result); else if (!mFileAdapter.isEmpty()) mViewFiles.setSelection(0); }// run() }, DisplayPrefs.DELAY_TIME_FOR_VERY_SHORT_ANIMATION); }// onPostExecute() }; mFileSelector.execute(); }
From source file:com.ehdev.chronos.lib.Chronos.java
@Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { try {/*from w ww . ja v a 2 s . c o m*/ Log.w(TAG, "Upgrading database, this will drop tables and recreate."); Log.w(TAG, "oldVerion: " + oldVersion + "\tnewVersion: " + newVersion); //Back up database try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/com.kopysoft.chronos/databases/" + DATABASE_NAME; String backupDBPath = DATABASE_NAME + ".db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.e(TAG, "ERROR: Can not move file"); } /* db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK + " ( _id INTEGER PRIMARY KEY NOT NULL, time LONG NOT NULL, actionReason INTEGER NOT NULL )"); db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE + " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )"); */ if (oldVersion < 15) { DateTime jobMidnight = DateTime.now().withDayOfWeek(7).minusWeeks(1).toDateMidnight().toDateTime() .withZone(DateTimeZone.getDefault()); Job currentJob = new Job("", 10, jobMidnight, PayPeriodDuration.TWO_WEEKS); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext); currentJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25"))); currentJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40"))); currentJob.setDoubletimeThreshold(Float.valueOf(pref.getString("double_time_threshold", "60"))); SharedPreferences.Editor edit = pref.edit(); edit.remove("8_or_40_hours"); //Moved from string to boolean edit.commit(); String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}"); jobMidnight = new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]), 0, 0); currentJob.setStartOfPayPeriod(jobMidnight.withZone(DateTimeZone.getDefault())); List<Punch> punches = new LinkedList<Punch>(); List<Task> tasks = new LinkedList<Task>(); List<Note> notes = new LinkedList<Note>(); Task newTask; //Basic element newTask = new Task(currentJob, 0, "Regular"); tasks.add(newTask); newTask = new Task(currentJob, 1, "Lunch Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 2, "Other Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 3, "Travel"); tasks.add(newTask); newTask = new Task(currentJob, 4, "Admin"); tasks.add(newTask); newTask = new Task(currentJob, 5, "Sick Leave"); tasks.add(newTask); newTask = new Task(currentJob, 6, "Personal Time"); tasks.add(newTask); newTask = new Task(currentJob, 7, "Other"); tasks.add(newTask); newTask = new Task(currentJob, 8, "Holiday Pay"); tasks.add(newTask); Cursor cursor = db.query("clockactions", null, null, null, null, null, "_id desc"); final int colTime = cursor.getColumnIndex("time"); final int colAR = cursor.getColumnIndex("actionReason"); if (cursor.moveToFirst()) { do { long time = cursor.getLong(colTime); Task type = tasks.get(0); if (colAR != -1) { type = tasks.get(cursor.getInt(colAR)); } punches.add(new Punch(currentJob, type, new DateTime(time))); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } cursor = db.query("notes", null, null, null, null, null, "_id desc"); final int colInsertTime = cursor.getColumnIndex("time"); final int colText = cursor.getColumnIndex("note_string"); if (cursor.moveToFirst()) { do { long time = cursor.getLong(colInsertTime); String note = cursor.getString(colText); notes.add(new Note(new DateTime(time), currentJob, note)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } db.execSQL("DROP TABLE IF EXISTS clockactions"); db.execSQL("DROP TABLE IF EXISTS notes"); db.execSQL("DROP TABLE IF EXISTS misc"); //Recreate DB TableUtils.createTable(connectionSource, Punch.class); //Punch - Create Table TableUtils.createTable(connectionSource, Task.class); //Task - Create Table TableUtils.createTable(connectionSource, Job.class); //Job - Create Table TableUtils.createTable(connectionSource, Note.class); //Task - Create Table //recreate entries Dao<Task, String> taskDAO = getTaskDao(); Dao<Job, String> jobDAO = getJobDao(); Dao<Note, String> noteDAO = getNoteDao(); Dao<Punch, String> punchDOA = getPunchDao(); jobDAO.create(currentJob); for (Task t : tasks) { taskDAO.create(t); } for (Note n : notes) { noteDAO.create(n); } for (Punch p : punches) { punchDOA.create(p); } //"CREATE TABLE " + TABLE_NAME_NOTE " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )"); } else if (oldVersion == 15) { //Drop //DB - 15 //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all //TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all Dao<Task, String> taskDAO = getTaskDao(); List<Task> tasks = taskDAO.queryForAll(); db.execSQL("DROP TABLE IF EXISTS tasks"); //create TableUtils.createTable(connectionSource, Task.class); //Task - Create Table for (Task t : tasks) { taskDAO.create(t); } } else if (oldVersion == 16) { //Drop //DB - 15 //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all //create TableUtils.createTable(connectionSource, Note.class); //Task - Create Table } else if (oldVersion == 17) { //update db from old version Dao<Job, String> dao = getJobDao(); dao.executeRaw("ALTER TABLE `jobs` ADD COLUMN fourtyHourWeek BOOLEAN DEFAULT 1;"); } else if (oldVersion == 18) { Dao<Task, String> taskDAO = getTaskDao(); List<Task> tasks = taskDAO.queryForAll(); Job currentJob = getAllJobs().get(0); if (tasks.size() == 0) { Task newTask; //Basic element newTask = new Task(currentJob, 0, "Regular"); tasks.add(newTask); newTask = new Task(currentJob, 1, "Lunch Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 2, "Other Break"); newTask.setEnablePayOverride(true); newTask.setPayOverride(-7.25f); tasks.add(newTask); newTask = new Task(currentJob, 3, "Travel"); tasks.add(newTask); newTask = new Task(currentJob, 4, "Admin"); tasks.add(newTask); newTask = new Task(currentJob, 5, "Sick Leave"); tasks.add(newTask); newTask = new Task(currentJob, 6, "Personal Time"); tasks.add(newTask); newTask = new Task(currentJob, 7, "Other"); tasks.add(newTask); newTask = new Task(currentJob, 8, "Holiday Pay"); tasks.add(newTask); for (Task t : tasks) { taskDAO.createOrUpdate(t); } } } else if (oldVersion == 19) { try { TableUtils.dropTable(connectionSource, Job.class, true); //Job - Create Table TableUtils.createTable(connectionSource, Job.class); //Job - Create Table DateTime jobMidnight = new DateMidnight().toDateTime().minusWeeks(1) .withZone(DateTimeZone.getDefault()); Job thisJob = new Job("", 7.25f, jobMidnight, PayPeriodDuration.TWO_WEEKS); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext); try { thisJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25"))); } catch (NumberFormatException e) { thisJob.setPayRate(7.25f); Log.d(TAG, e.getMessage()); } try { thisJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40"))); } catch (NumberFormatException e) { thisJob.setOvertime(40f); Log.d(TAG, e.getMessage()); } try { thisJob.setDoubletimeThreshold( Float.valueOf(pref.getString("double_time_threshold", "60"))); } catch (NumberFormatException e) { thisJob.setDoubletimeThreshold(60f); Log.d(TAG, e.getMessage()); } String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}"); String time[] = pref.getString("time", "00:00").split("\\p{Punct}"); thisJob.setStartOfPayPeriod(new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]))); switch (Integer.parseInt(pref.getString("len_of_month", "2"))) { case 1: thisJob.setDuration(PayPeriodDuration.ONE_WEEK); break; case 2: thisJob.setDuration(PayPeriodDuration.TWO_WEEKS); break; case 3: thisJob.setDuration(PayPeriodDuration.THREE_WEEKS); break; case 4: thisJob.setDuration(PayPeriodDuration.FOUR_WEEKS); break; case 5: thisJob.setDuration(PayPeriodDuration.FULL_MONTH); break; case 6: thisJob.setDuration(PayPeriodDuration.FIRST_FIFTEENTH); break; default: thisJob.setDuration(PayPeriodDuration.TWO_WEEKS); break; } getJobDao().create(thisJob); } catch (SQLException e1) { e1.printStackTrace(); } } else if (oldVersion == 20) { getJobDao().executeRaw( "ALTER TABLE 'jobs' ADD COLUMN '" + Job.OVERTIME_OPTIONS + "' VARCHAR default 'NONE';"); getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SATURDAY_OVERRIDE_FIELD + "' VARCHAR default 'NONE';"); getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SUNDAY_OVERRIDE_FIELD + "' VARCHAR default 'NONE';"); List<Job> jobList = getAllJobs(); for (Job job : jobList) { GenericRawResults<String[]> rawResults = getJobDao().queryRaw( "select fourtyHourWeek,overTimeEnabled from jobs where job_id = " + job.getID()); String[] results = rawResults.getResults().get(0); if (results[0] == "0") { job.setOvertimeOptions(OvertimeOptions.NONE); } else { if (results[1] == "0") { job.setOvertimeOptions(OvertimeOptions.DAY); } else if (results[1] == "1") { //being paranoid job.setOvertimeOptions(OvertimeOptions.WEEK); } } } //delete stuff getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'fourtyHourWeek';"); getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'overTimeEnabled';"); } } catch (SQLException e) { e.printStackTrace(); Log.e(TAG, "Could not upgrade the table for Thing", e); } }
From source file:org.ttrssreader.controllers.DBHelper.java
public Feed getFeed(int id) { Feed ret = new Feed(); if (!isDBAvailable()) return ret; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true);//from w w w .jav a 2s . c o m Cursor c = null; try { c = db.query(TABLE_FEEDS, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleFeedCursor(c); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get summary length of remote files, which are cached * * @return summary length of remote files *//*from w ww . j a v a 2 s.com*/ public long getCachedFilesSize() { if (!isDBAvailable()) return 0; long ret = 0; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { c = db.query(TABLE_REMOTEFILES, new String[] { "SUM(length)" }, "cached=1", null, null, null, null); if (c.moveToFirst()) ret = c.getLong(0); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:org.ttrssreader.controllers.DBHelper.java
public Article getArticle(int id) { Article ret = null;/*from ww w . j av a 2 s.c o m*/ if (!isDBAvailable()) return null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { c = db.query(TABLE_ARTICLES, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleArticleCursor(c); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:org.ttrssreader.controllers.DBHelper.java
public Category getCategory(int id) { Category ret = new Category(); if (!isDBAvailable()) return ret; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true);/*w w w . ja v a 2 s . c o m*/ Cursor c = null; try { c = db.query(TABLE_CATEGORIES, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleCategoryCursor(c); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:org.tigase.mobile.chat.ChatHistoryFragment.java
private void showMessageDetails(final long id) { Cursor cc = null; final java.text.DateFormat df = DateFormat.getDateFormat(getActivity()); final java.text.DateFormat tf = DateFormat.getTimeFormat(getActivity()); try {/* www . j a va2 s . co m*/ cc = getChatEntry(id); Dialog alertDialog = new Dialog(getActivity()); alertDialog.setContentView(R.layout.chat_item_details_dialog); alertDialog.setCancelable(true); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setTitle("Message details"); TextView msgDetSender = (TextView) alertDialog.findViewById(R.id.msgDetSender); msgDetSender.setText(cc.getString(cc.getColumnIndex(ChatTableMetaData.FIELD_JID))); Date timestamp = new Date(cc.getLong(cc.getColumnIndex(ChatTableMetaData.FIELD_TIMESTAMP))); TextView msgDetReceived = (TextView) alertDialog.findViewById(R.id.msgDetReceived); msgDetReceived.setText(df.format(timestamp) + " " + tf.format(timestamp)); final int state = cc.getInt(cc.getColumnIndex(ChatTableMetaData.FIELD_STATE)); TextView msgDetState = (TextView) alertDialog.findViewById(R.id.msgDetState); switch (state) { case ChatTableMetaData.STATE_INCOMING: msgDetState.setText("Received"); break; case ChatTableMetaData.STATE_OUT_SENT: msgDetState.setText("Sent"); break; case ChatTableMetaData.STATE_OUT_NOT_SENT: msgDetState.setText("Not sent"); break; default: msgDetState.setText("?"); break; } alertDialog.show(); } finally { if (cc != null && !cc.isClosed()) cc.close(); } }
From source file:com.ichi2.libanki.Stats.java
public boolean calculateDone(int type, boolean reps) { mHasColoredCumulative = true;/*from w w w. j a v a 2s . c o m*/ mDynamicAxis = true; mType = type; 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 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 == TYPE_MONTH) { 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 - " + 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"; Timber.d("ReviewCount query: %s", query); try { cur = mCol.getDb().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 != 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 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; mCumulative = new double[6][]; mCumulative[0] = mSeriesList[0]; for (int i = 1; i < mSeriesList.length; i++) { mCumulative[i] = createCumulative(mSeriesList[i]); if (i > 1) { for (int j = 0; j < mCumulative[i - 1].length; j++) { mCumulative[i - 1][j] -= mCumulative[i][j]; } } } switch (mType) { case TYPE_MONTH: mFirstElement = -31; break; case TYPE_YEAR: mFirstElement = -52; break; default: } mMcount = 0; // we could assume the last element to be the largest, // but on some collections that may not be true due some negative values //so we search for the largest element: for (int i = 1; i < mCumulative.length; i++) { for (int j = 0; j < mCumulative[i].length; j++) { if (mMcount < mCumulative[i][j]) mMcount = mCumulative[i][j]; } } //some adjustments to not crash the chartbuilding with emtpy data if (mMaxCards == 0) mMaxCards = 10; if (mMaxElements == 0) { mMaxElements = 10; } if (mMcount == 0) { mMcount = 10; } if (mFirstElement == mLastElement) { mFirstElement = -10; mLastElement = 0; } return list.size() > 0; }
From source file:me.myatminsoe.myansms.SmsReceiver.java
/** * Update failed message notification.//from ww w .j a va2 s . c om * * @param context {@link Context} * @param uri {@link Uri} to message */ private static void updateFailedNotification(final Context context, final Uri uri) { final Cursor c = context.getContentResolver().query(uri, Message.PROJECTION_SMS, null, null, null); if (c != null && c.moveToFirst()) { final int id = c.getInt(Message.INDEX_ID); final int tid = c.getInt(Message.INDEX_THREADID); final String body = c.getString(Message.INDEX_BODY); final long date = c.getLong(Message.INDEX_DATE); Conversation conv = Conversation.getConversation(context, tid, true); final NotificationManager mNotificationMgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); final boolean privateNotification = p.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false); Intent intent; if (conv == null) { intent = new Intent(Intent.ACTION_VIEW, null, context, SenderActivity.class); } else { intent = new Intent(Intent.ACTION_VIEW, conv.getUri(), context, MessageListActivity.class); } intent.putExtra(Intent.EXTRA_TEXT, body); String title = context.getString(R.string.error_sending_failed); final int[] ledFlash = PreferencesActivity.getLEDflash(context); final NotificationCompat.Builder b = new NotificationCompat.Builder(context) .setSmallIcon(android.R.drawable.stat_sys_warning).setTicker(title).setWhen(date) .setAutoCancel(true).setLights(RED, ledFlash[0], ledFlash[1]).setContentIntent( PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); String text; if (privateNotification) { title += "!"; text = ""; } else if (conv == null) { title += "!"; text = body; } else { title += ": " + conv.getContact().getDisplayName(); text = body; } b.setContentTitle(title); b.setContentText(text); final String s = p.getString(PreferencesActivity.PREFS_SOUND, null); if (!TextUtils.isEmpty(s)) { b.setSound(Uri.parse(s)); } final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false); if (vibrate) { final long[] pattern = PreferencesActivity.getVibratorPattern(context); if (pattern.length > 1) { b.setVibrate(pattern); } } mNotificationMgr.notify(id, b.build()); } if (c != null && !c.isClosed()) { c.close(); } }
From source file:com.haibison.android.anhuu.FragmentFiles.java
/** * Creates new {@link #mFileSelector} to select appropriate file after * loading a folder's content. It's either the parent path of last path, or * the file provided by key {@link FileChooserActivity#EXTRA_SELECT_FILE}. * Note that this also cancels previous selector if there is such one. *//* w ww . ja v a 2s . com*/ private void createFileSelector() { if (mFileSelector != null) mFileSelector.cancel(true); mFileSelector = new LoadingDialog<Void, Void, Integer>(getActivity(), true) { @Override protected Integer doInBackground(Void... params) { final Cursor cursor = mFileAdapter.getCursor(); if (cursor == null || cursor.isClosed()) return -1; final Uri selectedFile = (Uri) getArguments().getParcelable(FileChooserActivity.EXTRA_SELECT_FILE); final int colUri = cursor.getColumnIndex(BaseFile.COLUMN_URI); if (selectedFile != null) getArguments().remove(FileChooserActivity.EXTRA_SELECT_FILE); int shouldBeSelectedIdx = -1; final Uri uri = selectedFile != null ? selectedFile : getLastLocation(); if (uri == null || !BaseFileProviderUtils.fileExists(getActivity(), uri)) return -1; final String fileName = BaseFileProviderUtils.getFileName(getActivity(), uri); if (fileName == null) return -1; Uri parentUri = BaseFileProviderUtils.getParentFile(getActivity(), uri); if ((uri == getLastLocation() && !getCurrentLocation().equals(getLastLocation()) && BaseFileProviderUtils.isAncestorOf(getActivity(), getCurrentLocation(), uri)) || getCurrentLocation().equals(parentUri)) { if (cursor.moveToFirst()) { while (!cursor.isLast()) { if (isCancelled()) return -1; Uri subUri = Uri.parse(cursor.getString(colUri)); if (uri == getLastLocation()) { if (cursor.getInt(cursor .getColumnIndex(BaseFile.COLUMN_TYPE)) == BaseFile.FILE_TYPE_DIRECTORY) { if (subUri.equals(uri) || BaseFileProviderUtils.isAncestorOf(getActivity(), subUri, uri)) { shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2); break; } } } else { if (uri.equals(subUri)) { shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2); break; } } cursor.moveToNext(); } // while } // if } // if return shouldBeSelectedIdx; }// doInBackground() @Override protected void onPostExecute(final Integer result) { super.onPostExecute(result); if (isCancelled() || mFileAdapter.isEmpty()) return; /* * Use a Runnable to make sure this works. Because if the list * view is handling data, this might not work. * * Also sometimes it doesn't work without a delay. */ mViewFiles.postDelayed(new Runnable() { @Override public void run() { if (result >= 0 && result < mFileAdapter.getCount()) mViewFiles.setSelection(result); else if (!mFileAdapter.isEmpty()) mViewFiles.setSelection(0); }// run() }, Display.DELAY_TIME_FOR_VERY_SHORT_ANIMATION); }// onPostExecute() }; mFileSelector.execute(); }