List of usage examples for android.database Cursor getDouble
double getDouble(int columnIndex);
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the data stored in the cursor at the given index and given position * (ie the given row which the cursor is currently on) as null OR whatever * data type it is./*from www . j a v a2 s. c o m*/ * <p> * This does not actually convert data types from one type to the other. * Instead, it safely preserves null values and returns boxed data values. If * you specify ArrayList or HashMap, it JSON deserializes the value into one * of those. * * @param c * @param clazz * @param i * @return */ @SuppressLint("NewApi") public final <T> T getIndexAsType(Cursor c, Class<T> clazz, int i) { // If you add additional return types here be sure to modify the javadoc. try { if (i == -1) return null; if (c.isNull(i)) { return null; } if (clazz == Long.class) { Long l = c.getLong(i); return (T) l; } else if (clazz == Integer.class) { Integer l = c.getInt(i); return (T) l; } else if (clazz == Double.class) { Double d = c.getDouble(i); return (T) d; } else if (clazz == String.class) { String str = c.getString(i); return (T) str; } else if (clazz == Boolean.class) { // stored as integers Integer l = c.getInt(i); return (T) Boolean.valueOf(l != 0); } else if (clazz == ArrayList.class) { // json deserialization of an array String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, ArrayList.class); } else if (clazz == HashMap.class) { // json deserialization of an object String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, HashMap.class); } else { throw new IllegalStateException("Unexpected data type in SQLite table"); } } catch (ClassCastException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " in SQLite table "); } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } }
From source file:com.ternup.caddisfly.fragment.DetailsFragment.java
private void displayResult() { String[] projection = { TestTable.TABLE_TEST + "." + TestTable.COLUMN_ID, TestTable.TABLE_TEST + "." + TestTable.COLUMN_DATE, TestTable.COLUMN_RESULT, TestTable.COLUMN_TYPE, TestTable.COLUMN_FOLDER, LocationTable.COLUMN_NAME, LocationTable.COLUMN_STREET, LocationTable.COLUMN_TOWN, LocationTable.COLUMN_CITY, LocationTable.COLUMN_STATE, LocationTable.COLUMN_COUNTRY, LocationTable.COLUMN_STREET, LocationTable.COLUMN_SOURCE }; Log.d("Result", mId + " test"); Uri uri = ContentUris.withAppendedId(TestContentProvider.CONTENT_URI, mId); Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null); cursor.moveToFirst();//from w ww . ja v a 2s . c om if (cursor.getCount() > 0) { mAddressText.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_NAME)) + ", " + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STREET))); mAddress2Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_TOWN)) + ", " + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_CITY))); mAddress3Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STATE)) + ", " + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_COUNTRY))); if (mAddress2Text.getText().equals(", ")) { mAddress2Text.setVisibility(View.GONE); } else { mAddress2Text.setVisibility(View.VISIBLE); } if (mAddress3Text.getText().equals(", ")) { mAddress3Text.setVisibility(View.GONE); } else { mAddress3Text.setVisibility(View.VISIBLE); } String[] sourceArray = getResources().getStringArray(R.array.source_types); int sourceType = cursor.getInt(cursor.getColumnIndex(LocationTable.COLUMN_SOURCE)); if (sourceType > -1) { mSourceText.setText(sourceArray[sourceType]); mSourceText.setVisibility(View.VISIBLE); } else { mSourceText.setVisibility(View.GONE); } Date date = new Date(cursor.getLong(cursor.getColumnIndex(TestTable.COLUMN_DATE))); SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy"); DateFormat tf = android.text.format.DateFormat.getTimeFormat(getActivity()); // Gets system TF String dateString = df.format(date.getTime()) + ", " + tf.format(date.getTime()); mTestType = DataHelper.getTestTitle(getActivity(), cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE))); mTestTypeId = cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE)); mTitleView.setText(mTestType); mDateView.setText(dateString); Double resultPpm = cursor.getDouble(cursor.getColumnIndex(TestTable.COLUMN_RESULT)); if (mTestTypeId == Globals.PH_INDEX) { mPpmText.setText(""); } else { mPpmText.setText(R.string.ppm); } if (resultPpm < 0) { mResultTextView.setText("0.0"); //mResultIcon.setVisibility(View.GONE); mPpmText.setVisibility(View.GONE); } else { mResultTextView.setText(String.format("%.2f", resultPpm)); Context context = getActivity().getApplicationContext(); int resourceAttribute; if (resultPpm <= Globals.FLUORIDE_MAX_DRINK) { resourceAttribute = R.attr.drink; } else if (resultPpm <= Globals.FLUORIDE_MAX_COOK) { resourceAttribute = R.attr.cook; } else if (resultPpm <= Globals.FLUORIDE_MAX_BATHE) { resourceAttribute = R.attr.bath; } else { resourceAttribute = R.attr.wash; } TypedArray a = context.getTheme().obtainStyledAttributes( ((MainApp) context.getApplicationContext()).CurrentTheme, new int[] { resourceAttribute }); int attributeResourceId = a.getResourceId(0, 0); //mResultIcon.setImageResource(attributeResourceId); //mResultIcon.setVisibility(View.VISIBLE); mPpmText.setVisibility(View.VISIBLE); } } cursor.close(); }
From source file:com.ichi2.libanki.Sched.java
/** estimates remaining time for learning (based on last seven days) */ public int eta(int[] counts, boolean reload) { double revYesRate; double revTime; double lrnYesRate; double lrnTime; if (reload || mEtaCache[0] == -1) { Cursor cur = null; try {/*from w w w. j a v a 2s. c o m*/ cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease > 1 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type = 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } revYesRate = cur.getDouble(0); revTime = cur.getDouble(1); if (!cur.isClosed()) { cur.close(); } cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease = 3 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type != 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } lrnYesRate = cur.getDouble(0); lrnTime = cur.getDouble(1); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } mEtaCache[0] = revYesRate; mEtaCache[1] = revTime; mEtaCache[2] = lrnYesRate; mEtaCache[3] = lrnTime; } else { revYesRate = mEtaCache[0]; revTime = mEtaCache[1]; lrnYesRate = mEtaCache[2]; lrnTime = mEtaCache[3]; } // rev cards double eta = revTime * counts[2]; // lrn cards double factor = Math.min(1 / (1 - lrnYesRate), 10); double lrnAnswers = (counts[0] + counts[1] + counts[2] * (1 - revYesRate)) * factor; eta += lrnAnswers * lrnTime; return (int) (eta / 60000); }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
/** estimates remaining time for learning (based on last seven days) */ public int eta(int[] counts, boolean reload) { double revYesRate; double revTime; double lrnYesRate; double lrnTime; if (reload || mEtaCache[0] == -1) { Cursor cur = null; try {/* w w w . ja va 2s .c om*/ cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease > 1 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type = 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } revYesRate = cur.getDouble(0); revTime = cur.getDouble(1); cur = mCol.getDb().getDatabase().rawQuery( "SELECT avg(CASE WHEN ease = 3 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type != 1 AND id > " + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null); if (!cur.moveToFirst()) { return -1; } lrnYesRate = cur.getDouble(0); lrnTime = cur.getDouble(1); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } mEtaCache[0] = revYesRate; mEtaCache[1] = revTime; mEtaCache[2] = lrnYesRate; mEtaCache[3] = lrnTime; } else { revYesRate = mEtaCache[0]; revTime = mEtaCache[1]; lrnYesRate = mEtaCache[2]; lrnTime = mEtaCache[3]; } // rev cards double eta = revTime * counts[2]; // lrn cards double factor = Math.min(1 / (1 - lrnYesRate), 10); double lrnAnswers = (counts[0] + counts[1] + counts[2] * (1 - revYesRate)) * factor; eta += lrnAnswers * lrnTime; return (int) (eta / 60000); }
From source file:edu.pdx.cecs.orcycle.TripUploader.java
/** * Get all sensor readings corresponding to this time index * @return/* w w w . j a v a 2s . c o m*/ */ private JSONArray getJsonSensorReadings(double coordTime) { JSONArray jsonSensorReadings = null; JSONObject jsonSensorReading; int numVals; Cursor cursorSV = null; try { if (null != (cursorSV = mDb.fetchSensorValues(coordTime))) { // Collect sensor readings into a json object jsonSensorReadings = new JSONArray(); // Construct a map between cursor column index if (null == sensorColumn) { sensorColumn = new HashMap<String, Integer>(); sensorColumn.put(TRIP_COORD_SENSOR_ID, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_ID)); sensorColumn.put(TRIP_COORD_SENSOR_TYPE, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_TYPE)); sensorColumn.put(TRIP_COORD_SENSOR_SAMPLES, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_SAMPLES)); sensorColumn.put(TRIP_COORD_SENSOR_NUM_VALS, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_NUM_VALS)); sensorColumn.put(TRIP_COORD_SENSOR_AVG_0, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_AVG_0)); sensorColumn.put(TRIP_COORD_SENSOR_AVG_1, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_AVG_1)); sensorColumn.put(TRIP_COORD_SENSOR_AVG_2, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_AVG_2)); sensorColumn.put(TRIP_COORD_SENSOR_SSD_0, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_SSD_0)); sensorColumn.put(TRIP_COORD_SENSOR_SSD_1, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_SSD_1)); sensorColumn.put(TRIP_COORD_SENSOR_SSD_2, cursorSV.getColumnIndex(DbAdapter.K_SENSOR_SSD_2)); } int numSamples; while (!cursorSV.isAfterLast()) { jsonSensorReading = new JSONObject(); jsonSensorReading.put(TRIP_COORD_SENSOR_ID, cursorSV.getString(sensorColumn.get(TRIP_COORD_SENSOR_ID))); jsonSensorReading.put(TRIP_COORD_SENSOR_TYPE, cursorSV.getInt(sensorColumn.get(TRIP_COORD_SENSOR_TYPE))); jsonSensorReading.put(TRIP_COORD_SENSOR_SAMPLES, (numSamples = cursorSV.getInt(sensorColumn.get(TRIP_COORD_SENSOR_SAMPLES)))); numVals = cursorSV.getInt(sensorColumn.get(TRIP_COORD_SENSOR_NUM_VALS)); switch (numVals) { case 1: jsonSensorReading.put(TRIP_COORD_SENSOR_AVG_0, dr2(cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_AVG_0)))); if (numSamples > 0) { jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_0, dr2(Math.sqrt( cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_SSD_0)) / numSamples))); } else { jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_0, 0.0); } break; case 3: jsonSensorReading.put(TRIP_COORD_SENSOR_AVG_0, dr2(cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_AVG_0)))); jsonSensorReading.put(TRIP_COORD_SENSOR_AVG_1, dr2(cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_AVG_1)))); jsonSensorReading.put(TRIP_COORD_SENSOR_AVG_2, dr2(cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_AVG_2)))); if (numSamples > 0) { jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_0, dr2(Math.sqrt( cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_SSD_0)) / numSamples))); jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_1, dr2(Math.sqrt( cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_SSD_1)) / numSamples))); jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_2, dr2(Math.sqrt( cursorSV.getDouble(sensorColumn.get(TRIP_COORD_SENSOR_SSD_2)) / numSamples))); } else { jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_0, 0.0); jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_1, 0.0); jsonSensorReading.put(TRIP_COORD_SENSOR_SSD_2, 0.0); } break; } jsonSensorReadings.put(jsonSensorReading); cursorSV.moveToNext(); } } } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); } finally { if (null != cursorSV) { cursorSV.close(); } } return jsonSensorReadings; }
From source file:osu.appclub.corvallisbus.MainActivity.java
@Override public void searchComplete(Cursor cursor) { Log.d("osu.appclub", "Found " + cursor.getCount() + " results"); if (cursor.getCount() == 0) { MatrixCursor placeholder = new MatrixCursor(new String[] { "_id" }); placeholder.addRow(new Object[] { 0 }); searchView.setSuggestionsAdapter(new CursorAdapter(this, placeholder, false) { @Override//w w w .ja v a 2 s .c om public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView text = (TextView) view.findViewById(android.R.id.text1); text.setText(R.string.search_no_results); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // no-op } }); } }); } else { searchView.setSuggestionsAdapter(new CursorAdapter(this, cursor, false) { @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); return view; } @SuppressLint("DefaultLocale") @Override public void bindView(View view, Context context, Cursor cursor) { final int stopID = cursor.getInt(0); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchView.clearFocus(); enqueueBusStop(stopID); } }); TextView textStopName = (TextView) view.findViewById(android.R.id.text1); textStopName.setText(cursor.getString(1)); TextView textDistance = (TextView) view.findViewById(android.R.id.text2); if (cursor.getType(2) == Cursor.FIELD_TYPE_NULL) { textDistance.setText(""); } else { textDistance.setText(String.format("%.1f miles", cursor.getDouble(2))); } } }); } }
From source file:gov.cdc.epiinfo.RecordList.java
private void editRecord(long id) { Cursor c = mDbHelper.fetchRecord(id); AppManager.SetCurrentDatabase(mDbHelper); c.moveToPosition(0);// w w w. j a v a 2s .c o m waitDialog = ProgressDialog.show(this, getString(R.string.loading_form), getString(R.string.please_wait), true); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); boolean useInterviewMode = sharedPref.getBoolean("interview", false) || formMetadata.IsInterviewForm; Intent i; if (useInterviewMode) { i = new Intent(this, Interviewer.class); } else { i = new Intent(this, RecordEditor.class); } i.putExtra(EpiDbHelper.KEY_ROWID, id); i.putExtra(EpiDbHelper.GUID, c.getString(c.getColumnIndexOrThrow(EpiDbHelper.GUID))); for (int x = 0; x < formMetadata.DataFields.size(); x++) { if (formMetadata.DataFields.get(x).getType().equals("10") || formMetadata.DataFields.get(x).getType().equals("11") || formMetadata.DataFields.get(x).getType().equals("12") || formMetadata.DataFields.get(x).getType().equals("18") || formMetadata.DataFields.get(x).getType().equals("19")) { String fieldName = formMetadata.DataFields.get(x).getName(); int columnIndex = c.getColumnIndexOrThrow(fieldName); int value = c.getInt(columnIndex); i.putExtra(fieldName, value); } else if (formMetadata.DataFields.get(x).getType().equals("17")) { if (formMetadata.DataFields.get(x).getListValues().size() > 100) { String fieldName = formMetadata.DataFields.get(x).getName(); int columnIndex = c.getColumnIndexOrThrow(fieldName); String value = c.getString(columnIndex); i.putExtra(fieldName, value); } else { String fieldName = formMetadata.DataFields.get(x).getName(); int columnIndex = c.getColumnIndexOrThrow(fieldName); int value = c.getInt(columnIndex); i.putExtra(fieldName, value); } } else if (formMetadata.DataFields.get(x).getType().equals("5")) { String fieldName = formMetadata.DataFields.get(x).getName(); int columnIndex = c.getColumnIndexOrThrow(fieldName); double value = c.getDouble(columnIndex); i.putExtra(fieldName, value); } else { String fieldName = formMetadata.DataFields.get(x).getName(); int columnIndex = c.getColumnIndexOrThrow(fieldName); String value = c.getString(columnIndex); i.putExtra(fieldName, value); } } new PreCompiledLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, i); }
From source file:fr.eoit.activity.util.StationListViewBinder.java
@Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); boolean isNull = cursor.isNull(columnIndex); TextView textView;/*from w w w. j ava2 s. co m*/ ImageView imageView; String[] stationNameArray; double price; long volume; int role, stationId = cursor.getInt(cursor.getColumnIndexOrThrow(Station._ID)); switch (viewId) { case R.id.station_name: stationName = cursor.getString(columnIndex); textView = (TextView) view; stationNameArray = stationName.split(" - "); textView.setText(stationNameArray[stationNameArray.length - 1]); break; case R.id.location_name: String regionName = cursor.getString(columnIndex); textView = (TextView) view; stationNameArray = stationName.split(" - "); StringBuilder sb = new StringBuilder(regionName); if (stationNameArray.length == 2) { sb.append(" > ").append(stationNameArray[0]); } else if (stationNameArray.length == 3) { sb.append(" > ").append(stationNameArray[0]).append(" - ").append(stationNameArray[1]); } textView.setText(sb.toString()); break; case R.id.station_icon: int id = cursor.getInt(columnIndex); imageView = (ImageView) view; IconUtil.initRender(id, imageView); break; case R.id.favorite_station: boolean favorite = cursor.getInt(columnIndex) == 1; CheckBox favoriteCheckBox = (CheckBox) view; favoriteCheckBox.setChecked(favorite); favoriteCheckBox.setOnCheckedChangeListener( new FavoriteStationsOnCheckedChangeListener(stationId, favoriteCheckBox.getContext())); break; case R.id.station_prod_icon: role = cursor.getInt(columnIndex); imageView = (ImageView) view; if (role == EOITConst.Stations.TRADE_ROLE || isNull) { view.setVisibility(View.GONE); } else { view.setVisibility(View.VISIBLE); } break; case R.id.station_trade_icon: role = cursor.getInt(columnIndex); imageView = (ImageView) view; if (role == EOITConst.Stations.PRODUCTION_ROLE || isNull) { view.setVisibility(View.GONE); } else { view.setVisibility(View.VISIBLE); } break; case R.id.corp_standing: float standing = cursor.getFloat(columnIndex); textView = (TextView) view; textView.setText(nf.format(standing)); if (standing > 0) { textView.setTextColor(view.getResources().getColor(R.color.green)); } else if (standing == 0) { textView.setTextColor(view.getResources().getColor(R.color.grey)); } else if (standing < 0) { textView.setTextColor(view.getResources().getColor(R.color.red)); } break; case R.id.buy_price: case R.id.sell_price: price = cursor.getDouble(columnIndex); textView = (TextView) view; PricesUtils.setPrice(textView, price, true); break; case R.id.buy_volume: case R.id.sell_volume: volume = cursor.getLong(columnIndex); textView = (TextView) view; textView.setText(nfVolume.format(volume)); break; default: throw new IllegalArgumentException("viewId : " + viewId); } return true; }
From source file:com.battlelancer.seriesguide.ui.EpisodeDetailsFragment.java
private void populateEpisodeData(Cursor cursor) { if (cursor == null || !cursor.moveToFirst()) { // no data to display if (mEpisodeContainer != null) { mEpisodeContainer.setVisibility(View.GONE); }// w ww .jav a2s. c om return; } mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID); mSeasonNumber = cursor.getInt(DetailsQuery.SEASON); mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER); mShowRunTime = cursor.getInt(DetailsQuery.SHOW_RUNTIME); mEpisodeReleaseTime = cursor.getLong(DetailsQuery.FIRST_RELEASE_MS); // title and description mEpisodeTitle = cursor.getString(DetailsQuery.TITLE); mTitle.setText(mEpisodeTitle); mDescription.setText(cursor.getString(DetailsQuery.OVERVIEW)); // show title mShowTitle = cursor.getString(DetailsQuery.SHOW_TITLE); // release time and day SpannableStringBuilder timeAndNumbersText = new SpannableStringBuilder(); if (mEpisodeReleaseTime != -1) { Date actualRelease = TimeTools.getEpisodeReleaseTime(getActivity(), mEpisodeReleaseTime); mReleaseDay.setText(TimeTools.formatToDate(getActivity(), actualRelease)); // "in 15 mins (Fri)" timeAndNumbersText.append(getString(R.string.release_date_and_day, TimeTools.formatToRelativeLocalReleaseTime(getActivity(), actualRelease), TimeTools.formatToLocalReleaseDay(actualRelease)).toUpperCase(Locale.getDefault())); timeAndNumbersText.append(" "); } else { mReleaseDay.setText(R.string.unknown); } // absolute number (e.g. relevant for Anime): "ABSOLUTE 142" int numberStartIndex = timeAndNumbersText.length(); int absoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER); if (absoluteNumber > 0) { timeAndNumbersText.append(getString(R.string.episode_number_absolute)).append(" ") .append(String.valueOf(absoluteNumber)); // de-emphasize number timeAndNumbersText.setSpan(new TextAppearanceSpan(getActivity(), R.style.TextAppearance_Caption_Dim), numberStartIndex, timeAndNumbersText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } mReleaseTime.setText(timeAndNumbersText); // guest stars Utils.setLabelValueOrHide(mLabelGuestStars, mGuestStars, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS))); // DVD episode number Utils.setLabelValueOrHide(mLabelDvd, mDvd, cursor.getDouble(DetailsQuery.DVDNUMBER)); // directors Utils.setValueOrPlaceholder(mDirectors, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS))); // writers Utils.setValueOrPlaceholder(mWriters, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS))); // last TVDb edit date long lastEditSeconds = cursor.getLong(DetailsQuery.LASTEDIT); if (lastEditSeconds > 0) { mLastEdit.setText(DateUtils.formatDateTime(getActivity(), lastEditSeconds * 1000, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME)); } else { mLastEdit.setText(R.string.unknown); } // ratings mRatingsContainer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { rateOnTrakt(); } }); mRatingsContainer.setFocusable(true); CheatSheet.setup(mRatingsContainer, R.string.action_rate); // TVDb rating String tvdbRating = cursor.getString(DetailsQuery.RATING); if (!TextUtils.isEmpty(tvdbRating)) { mTvdbRating.setText(tvdbRating); } // trakt ratings loadTraktRatings(true); // episode image final String imagePath = cursor.getString(DetailsQuery.IMAGE); mImageContainer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class); fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath); ActivityCompat.startActivity(getActivity(), fullscreen, ActivityOptionsCompat .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle()); } }); loadImage(imagePath); // check in button final int episodeTvdbId = cursor.getInt(DetailsQuery._ID); mCheckinButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // display a check-in dialog CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId); f.show(getFragmentManager(), "checkin-dialog"); fireTrackerEvent("Check-In"); } }); CheatSheet.setup(mCheckinButton); // watched button mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED); boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag); Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mWatchedButton, 0, isWatched ? Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatched) : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch), 0, 0); mWatchedButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // disable button, will be re-enabled on data reload once action completes v.setEnabled(false); onToggleWatched(); fireTrackerEvent("Toggle watched"); } }); mWatchedButton.setEnabled(true); mWatchedButton.setText(isWatched ? R.string.action_unwatched : R.string.action_watched); CheatSheet.setup(mWatchedButton, isWatched ? R.string.action_unwatched : R.string.action_watched); // collected button mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1; Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mCollectedButton, 0, mCollected ? R.drawable.ic_collected : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableCollect), 0, 0); mCollectedButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // disable button, will be re-enabled on data reload once action completes v.setEnabled(false); onToggleCollected(); fireTrackerEvent("Toggle collected"); } }); mCollectedButton.setEnabled(true); mCollectedButton.setText(mCollected ? R.string.action_collection_remove : R.string.action_collection_add); CheatSheet.setup(mCollectedButton, mCollected ? R.string.action_collection_remove : R.string.action_collection_add); // skip button boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag); if (isWatched) { // if watched do not allow skipping mSkipButton.setVisibility(View.INVISIBLE); } else { mSkipButton.setVisibility(View.VISIBLE); Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mSkipButton, 0, isSkipped ? R.drawable.ic_skipped : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip), 0, 0); mSkipButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // disable button, will be re-enabled on data reload once action completes v.setEnabled(false); onToggleSkipped(); fireTrackerEvent("Toggle skipped"); } }); mSkipButton.setText(isSkipped ? R.string.action_dont_skip : R.string.action_skip); CheatSheet.setup(mSkipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip); } mSkipButton.setEnabled(true); // service buttons ServiceUtils.setUpTraktButton(mShowTvdbId, mSeasonNumber, mEpisodeNumber, mTraktButton, TAG); // IMDb String imdbId = cursor.getString(DetailsQuery.IMDBID); if (TextUtils.isEmpty(imdbId)) { // fall back to show IMDb id imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID); } ServiceUtils.setUpImdbButton(imdbId, mImdbButton, TAG, getActivity()); // TVDb final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID); ServiceUtils.setUpTvdbButton(mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), mTvdbButton, TAG); // trakt comments mCommentsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), TraktShoutsActivity.class); intent.putExtras(TraktShoutsActivity.createInitBundleEpisode(mShowTvdbId, mSeasonNumber, mEpisodeNumber, mEpisodeTitle)); ActivityCompat.startActivity(getActivity(), intent, ActivityOptionsCompat .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle()); fireTrackerEvent("Comments"); } }); mEpisodeContainer.setVisibility(View.VISIBLE); }
From source file:pl.selvin.android.syncframework.content.TableInfo.java
public void GetChanges(SQLiteDatabase db, JsonGenerator gen, ArrayList<TableInfo> notifyTableInfo) throws IOException { String[] cols = new String[columns.length + 3]; int i = 0;/*from w w w. j a va2 s . co m*/ for (; i < columns.length; i++) cols[i] = columns[i].name; cols[i] = _.uri; cols[i + 1] = _.tempId; cols[i + 2] = _.isDeleted; Cursor c = db.query(name, cols, _.isDirtyP, new String[] { "1" }, null, null, null); //to fix startPos > actual rows for large cursors db operations should be done after cursor is closed ... final ArrayList<OperationHolder> operations = new ArrayList<OperationHolder>(); if (c.moveToFirst()) { if (!notifyTableInfo.contains(this)) notifyTableInfo.add(this); do { gen.writeStartObject(); gen.writeObjectFieldStart(_.__metadata); gen.writeBooleanField(_.isDirty, true); gen.writeStringField(_.type, scope_name); //Log.d("before", scope_name + ":" + c.getLong(i + 3)); String uri = c.getString(i); //Log.d("after", scope_name + ":" + c.getLong(i + 3)); if (uri == null) { gen.writeStringField(_.tempId, c.getString(i + 1)); } else { gen.writeStringField(_.uri, uri); final ContentValues update = new ContentValues(1); update.put(_.isDirty, 0); operations.add(new OperationHolder(name, OperationHolder.UPDATE, update, uri)); } boolean isDeleted = c.getInt(i + 2) == 1; if (isDeleted) { gen.writeBooleanField(_.isDeleted, true); gen.writeEndObject();// meta operations.add(new OperationHolder(name, OperationHolder.DELETE, null, uri)); } else { gen.writeEndObject();// meta for (i = 0; i < columns.length; i++) { if (columns[i].nullable && c.isNull(i)) { gen.writeNullField(columns[i].name); } else { switch (columns[i].type) { case ColumnType.BLOB: gen.writeBinaryField(columns[i].name, c.getBlob(i)); break; case ColumnType.BOOLEAN: gen.writeBooleanField(columns[i].name, c.getLong(i) == 1); break; case ColumnType.INTEGER: gen.writeNumberField(columns[i].name, c.getLong(i)); break; case ColumnType.DATETIME: try { gen.writeStringField(columns[i].name, String.format(msdate, sdf.parse(c.getString(i)).getTime())); } catch (Exception e) { if (BuildConfig.DEBUG) { Log.e("ListSync", e.getLocalizedMessage()); } } break; case ColumnType.NUMERIC: gen.writeNumberField(columns[i].name, c.getDouble(i)); break; default: gen.writeStringField(columns[i].name, c.getString(i)); break; } } } } gen.writeEndObject(); // end of row } while (c.moveToNext()); } c.close(); for (OperationHolder operation : operations) operation.execute(db); }