List of usage examples for android.text.format Time getJulianDay
public static int getJulianDay(long millis, long gmtoff)
From source file:com.example.binht.thoitiet.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/>/*w ww. j a v a 2s. c om*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private Void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } // // Sort order: Ascending, by date. // String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; // Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate( // locationSetting, System.currentTimeMillis()); // // // Students: Uncomment the next lines to display what what you stored in the bulkInsert // // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); // // String[] resultStrs = convertContentValuesToUXFormat(cVVector); // return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.example.dhrumil.sunshine.app.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from w w w.j a va 2 s . co m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); // mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); // } // // // Sort order: Ascending, by date. // String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; // Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate( // locationSetting, System.currentTimeMillis()); // // // Students: Uncomment the next lines to display what what you stored in the bulkInsert // // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } //Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); // String[] resultStrs = convertContentValuesToUXFormat(cVVector); // return resultStrs; Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } //return null; }
From source file:co.carlosjimenez.android.currencyalerts.app.DetailActivityFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data == null) { Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned"); return;/*from w w w.j a v a2 s. co m*/ } if (!data.moveToFirst()) { Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned"); data.close(); return; } long lDate = 0; String sDate = ""; String sCurrency = ""; int i = 0; double dRateAverage = 0; double dVal = 0; double dMinVal = 0; double dMaxVal = 0; data.moveToPosition(0); mCurrencyFromId = data.getString(COL_CURRENCY_FROM_ID); String currencyFromName = data.getString(COL_CURRENCY_FROM_NAME); String currencyFromSymbol = data.getString(COL_CURRENCY_FROM_SYMBOL); String countryFromName = data.getString(COL_COUNTRY_FROM_NAME); double currencyFromRate = ForexContract.RateEntry.getRateFromUri(mUri); mCurrencyToId = data.getString(COL_CURRENCY_TO_ID); String currencyToName = data.getString(COL_CURRENCY_TO_NAME); String currencyToSymbol = data.getString(COL_CURRENCY_TO_SYMBOL); String countryToName = data.getString(COL_COUNTRY_TO_NAME); double currencyToRate = ForexContract.RateEntry.getRateFromUri(mUri) * data.getDouble(COL_RATE_VAL); Glide.with(getActivity()).load(data.getString(COL_COUNTRY_FROM_FLAG)).error(R.drawable.globe).crossFade() .into(mIvFlagFrom); mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryFromName)); Glide.with(getActivity()).load(data.getString(COL_COUNTRY_TO_FLAG)).error(R.drawable.globe).crossFade() .into(mIvFlagTo); mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryToName)); mTvCurrencyFromDesc.setText(currencyFromName); mTvCurrencyFromDesc.setContentDescription(currencyFromName); mTvCurrencyFromRate .setText(Utility.formatCurrencyRate(getActivity(), currencyFromSymbol, currencyFromRate)); mTvCurrencyFromRate.setContentDescription(String.valueOf(currencyFromRate) + " " + currencyFromName); mTvCurrencyToDesc.setText(currencyToName); mTvCurrencyToDesc.setContentDescription(currencyToName); mTvCurrencyToRate.setText(Utility.formatCurrencyRate(getActivity(), currencyToSymbol, currencyToRate)); mTvCurrencyToRate.setContentDescription(String.valueOf(currencyToRate) + " " + currencyToName); Time dayTime = new Time(); dayTime.setToNow(); int julianDate = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); dayTime = new Time(); long lMinDate = dayTime.setJulianDay(julianDate - DEFAULT_DAYS_FOREX_AVERAGE); sDate = Utility.getDateString(getActivity(), data.getLong(COL_RATE_DATE)); for (i = 0; i < data.getCount() && i < DEFAULT_DAYS_FOREX_AVERAGE; i++) { data.moveToPosition(i); lDate = data.getLong(COL_RATE_DATE); if (lDate < lMinDate) { break; } sCurrency = data.getString(COL_CURRENCY_TO_ID); sDate = Utility.getDateString(getActivity(), lDate); dVal = data.getDouble(COL_RATE_VAL); dRateAverage += dVal; if (i == 0) { dMinVal = dVal; dMaxVal = dVal; } else { dMinVal = dMinVal < dVal ? dMinVal : dVal; dMaxVal = dMaxVal > dVal ? dMaxVal : dVal; } } dRateAverage = dRateAverage / i; if (data.getCount() > 1) mTvPeriod.setText(data.getCount() + " days"); else mTvPeriod.setText(data.getCount() + " day"); mTvMaxRate.setContentDescription(mTvPeriod.getText()); mTvMaxRate.setText( Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMaxVal)); mTvMaxRate.setContentDescription(mTvMaxRate.getText()); mTvMinRate.setText( Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMinVal)); mTvMinRate.setContentDescription(mTvMinRate.getText()); mTvAverageRate.setText( Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dRateAverage)); mTvAverageRate.setContentDescription(mTvAverageRate.getText()); // String text to share if user clicks on share menu icon mDisplayedRate = String.format("%s - %s %s = %s %s", sDate, currencyFromRate, mCurrencyFromId, currencyToRate, mCurrencyToId); mDisplayedCurrencyIds = mCurrencyFromId + "-" + mCurrencyToId; mDisplayedCurrencyNames = currencyToName; mContext.supportStartPostponedEnterTransition(); if (null != mToolbar) { Menu menu = mToolbar.getMenu(); if (null != menu) menu.clear(); mToolbar.inflateMenu(R.menu.detailfragment); finishCreatingMenu(mToolbar.getMenu()); } }
From source file:dk.larsbak.sunshine.ForecastFragment.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from w w w .j a v a 2 s. c o m*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; // Data is fetched in Celsius by default. // If user prefers to see in Fahrenheit, convert the values here. // We do this rather than fetching in Fahrenheit so that the user can // change this option without us having to re-fetch the data once // we start storing the values in a database. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); String unitType = sharedPrefs.getString(getString(R.string.pref_units_key), getString(R.string.pref_units_metric)); for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low, unitType); resultStrs[i] = day + " - " + description + " - " + highAndLow; } for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " + s); } return resultStrs; }
From source file:com.mio.jrdv.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./* w w w . j a v a 2s. c o m*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } //////////////////////////////////////////////////////////////////////////////////////////// ////// //////////////////////////////////////////////////////////////////////////////////////////// //////NO SE USA SE PASA AL FORECAST ADAPTER // The lines in getWeatherDataFromJson where we requery the database after the insert. //vamoa acambiarlo por el nuevo FroreCastAdapter!!: //////////////////////////////////////////////////////////////////////////////////////////// // // add to database // if ( cVVector.size() > 0 ) { // // Student: call bulkInsert to add the weatherEntries to the database here // // ContentValues[] cvArray = new ContentValues[cVVector.size()]; // cVVector.toArray(cvArray); // mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); // // // } // // // Sort order: Ascending, by date. // String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; // Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate( // locationSetting, System.currentTimeMillis()); // // // Students: Uncomment the next lines to display what what you stored in the bulkInsert // //esto no hace nada !!lo que hace es que inserte 0!!!! si no lo hacemos por medio un bulkinsert!! // // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } // // Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); // // String[] resultStrs = convertContentValuesToUXFormat(cVVector); // return resultStrs; int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.android.calendar.month.MonthByWeekFragment.java
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (mIsMiniMonth) { return null; }/*from w w w .j av a 2 s .co m*/ CursorLoader loader; synchronized (mUpdateLoader) { mFirstLoadedJulianDay = Time.getJulianDay(mSelectedDay.toMillis(true), mSelectedDay.gmtoff) - (mNumWeeks * 7 / 2); mEventUri = updateUri(); String where = updateWhere(); loader = new CursorLoader(getActivity(), mEventUri, Event.EVENT_PROJECTION, where, null /* WHERE_CALENDARS_SELECTED_ARGS */, INSTANCES_SORT_ORDER); loader.setUpdateThrottle(LOADER_THROTTLE_DELAY); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Returning new loader with uri: " + mEventUri); } return loader; }
From source file:co.carlosjimenez.android.currencyalerts.app.sync.ForexSyncAdapter.java
/** * Take the String representing the complete forex in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/>/*w w w .j a va2s . c om*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getForexDataFromJson(String forexJsonStr, String currencyQuery) throws JSONException { // Now we have a String representing the complete forex in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. final String OWM_RESULT = "results"; final String OWM_RATE_FROM = "fr"; final String OWM_RATE_TO = "to"; final String OWM_RATE = "val"; String[] currencies; boolean alertAvailable = false; try { if (mAlertData != null && mAlertData.getCurrencyFrom() != null && mAlertData.getCurrencyTo() != null) { alertAvailable = true; } JSONObject forexJson = new JSONObject(forexJsonStr); // do we have an error? if (!forexJson.has(OWM_RESULT)) { setForexStatus(getContext(), FOREX_STATUS_INVALID); return; } currencies = currencyQuery.split(","); JSONObject forexResultObject = forexJson.getJSONObject(OWM_RESULT); // OWM returns daily rates based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our rates. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianDate = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); long dateTime = dayTime.setJulianDay(julianDate); // Insert the new rates information into the database Vector<ContentValues> cVVector = new Vector<>(currencies.length); for (int i = 0; i < currencies.length; i++) { JSONObject currencyObject = forexResultObject.getJSONObject(currencies[i]); String rate_from = currencyObject.getString(OWM_RATE_FROM); String rate_to = currencyObject.getString(OWM_RATE_TO); double result = currencyObject.getDouble(OWM_RATE); ContentValues forexValues = new ContentValues(); forexValues.put(ForexContract.RateEntry.COLUMN_RATE_FROM_KEY, rate_from); forexValues.put(ForexContract.RateEntry.COLUMN_RATE_TO_KEY, rate_to); forexValues.put(ForexContract.RateEntry.COLUMN_RATE_DATE, dateTime); forexValues.put(ForexContract.RateEntry.COLUMN_RATE_VALUE, result); if (alertAvailable && mAlertData.getCurrencyFrom().getId().equals(rate_from) && mAlertData.getCurrencyTo().getId().equals(rate_to)) { mCurrentAlertRate = result; } cVVector.add(forexValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); getContext().getContentResolver().bulkInsert(ForexContract.RateEntry.CONTENT_URI, cvArray); // delete old data so we don't build up an endless history getContext().getContentResolver().delete(ForexContract.RateEntry.CONTENT_URI, ForexContract.RateEntry.COLUMN_RATE_DATE + " <= ?", new String[] { Long.toString(dayTime.setJulianDay(julianDate - FOREX_DAYS_TO_KEEP)) }); setForexSyncDate(getContext(), System.currentTimeMillis()); sendSyncBroadcast(FOREX_STATUS_OK); checkCurrencyData(); } Log.d(LOG_TAG, "ForexSyncAdapter: Sync Complete. " + cVVector.size() + " Inserted"); setForexStatus(getContext(), FOREX_STATUS_OK); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); setForexStatus(getContext(), FOREX_STATUS_SERVER_INVALID); } }
From source file:com.xandy.calendar.month.SimpleDayPickerFragment.java
/** * This moves to the specified time in the view. If the time is not already * in range it will move the list so that the first of the month containing * the time is at the top of the view. If the new time is already in view * the list will not be scrolled unless forceScroll is true. This time may * optionally be highlighted as selected as well. * * @param time The time to move to//from w w w . jav a2 s .co m * @param animate Whether to scroll to the given time or just redraw at the * new location * @param setSelected Whether to set the given time as selected * @param forceScroll Whether to recenter even if the time is already * visible * @return Whether or not the view animated to the new location */ public boolean goTo(long time, boolean animate, boolean setSelected, boolean forceScroll) { if (time == -1) { Log.e(TAG, "time is invalid"); return false; } // Set the selected day if (setSelected) { mSelectedDay.set(time); mSelectedDay.normalize(true); } // If this view isn't returned yet we won't be able to load the lists // current position, so return after setting the selected day. if (!isResumed()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "We're not visible yet"); } return false; } mTempTime.set(time); long millis = mTempTime.normalize(true); // Get the week we're going to // TODO push Util function into Calendar public api. int position = Utils.getWeeksSinceEpochFromJulianDay(Time.getJulianDay(millis, mTempTime.gmtoff), mFirstDayOfWeek); View child; int i = 0; int top = 0; // Find a child that's completely in the view do { child = mListView.getChildAt(i++); if (child == null) { break; } top = child.getTop(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "child at " + (i - 1) + " has top " + top); } } while (top < 0); // Compute the first and last position visible int firstPosition; if (child != null) { firstPosition = mListView.getPositionForView(child); } else { firstPosition = 0; } int lastPosition = firstPosition + mNumWeeks - 1; if (top > BOTTOM_BUFFER) { lastPosition--; } if (setSelected) { mAdapter.setSelectedDay(mSelectedDay); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "GoTo position " + position); } // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position < firstPosition || position > lastPosition || forceScroll) { mFirstDayOfMonth.set(mTempTime); mFirstDayOfMonth.monthDay = 1; millis = mFirstDayOfMonth.normalize(true); setMonthDisplayed(mFirstDayOfMonth, true); position = Utils.getWeeksSinceEpochFromJulianDay(Time.getJulianDay(millis, mFirstDayOfMonth.gmtoff), mFirstDayOfWeek); mPreviousScrollState = OnScrollListener.SCROLL_STATE_FLING; if (animate) { mListView.smoothScrollToPositionFromTop(position, LIST_TOP_OFFSET, GOTO_SCROLL_DURATION); return true; } else { mListView.setSelectionFromTop(position, LIST_TOP_OFFSET); // Perform any after scroll operations that are needed onScrollStateChanged(mListView, OnScrollListener.SCROLL_STATE_IDLE); } } else if (setSelected) { // Otherwise just set the selection setMonthDisplayed(mSelectedDay, true); } return false; }
From source file:me.zhang.bingo.Utility.java
/** * Helper method to convert the database representation of the date into something to display * to users. As classy and polished a user experience as "20170701" is, we can do better. * * @param context Context to use for resource localization * @param rawStartDate The date string: "20170701" * @return a user-friendly representation of the date. *///from w ww . ja v a 2s.c o m public static String getFriendlyDayString(Context context, String rawStartDate) { // The day string for forecast uses the following logic: // For today: "Today, July 1" // For yesterday: "Yesterday" // For all days before that: "Wed Jun 28" Time time = new Time(); time.setToNow(); long currentTime = System.currentTimeMillis(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, getChoosedLocale(context)); long dateInMillis = 0; try { dateInMillis = sdf.parse(rawStartDate).getTime(); } catch (ParseException e) { e.printStackTrace(); } int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff); int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff); if (julianDay == currentJulianDay) { // Today String today = context.getString(R.string.today); return context.getString(R.string.format_full_friendly_date, today, getFormattedMonthDay(context, dateInMillis)); } else if (julianDay == currentJulianDay - 1) { // Yesterday return context.getString(R.string.yesterday); } else { // Otherwise, use the form "Jun 28" SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("MMM d", getChoosedLocale(context)); return shortenedDateFormat.format(dateInMillis); } }
From source file:com.android.calendar.month.SimpleDayPickerFragment.java
/** * This moves to the specified time in the view. If the time is not already * in range it will move the list so that the first of the month containing * the time is at the top of the view. If the new time is already in view * the list will not be scrolled unless forceScroll is true. This time may * optionally be highlighted as selected as well. * * @param time//from w w w . j a v a 2 s. co m * The time to move to * @param animate * Whether to scroll to the given time or just redraw at the new * location * @param setSelected * Whether to set the given time as selected * @param forceScroll * Whether to recenter even if the time is already visible * @return Whether or not the view animated to the new location */ public boolean goTo(long time, boolean animate, boolean setSelected, boolean forceScroll) { if (time == -1) { Log.e(TAG, "time is invalid"); return false; } // Set the selected day if (setSelected) { mSelectedDay.set(time); mSelectedDay.normalize(true); } // If this view isn't returned yet we won't be able to load the lists // current position, so return after setting the selected day. if (!isResumed()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "We're not visible yet"); } return false; } mTempTime.set(time); long millis = mTempTime.normalize(true); // Get the week we're going to // TODO push Util function into Calendar public api. int position = Utils.getWeeksSinceEpochFromJulianDay(Time.getJulianDay(millis, mTempTime.gmtoff), mFirstDayOfWeek); View child; int i = 0; int top = 0; // Find a child that's completely in the view do { child = mListView.getChildAt(i++); if (child == null) { break; } top = child.getTop(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "child at " + (i - 1) + " has top " + top); } } while (top < 0); // Compute the first and last position visible int firstPosition; if (child != null) { firstPosition = mListView.getPositionForView(child); } else { firstPosition = 0; } int lastPosition = firstPosition + mNumWeeks - 1; if (top > BOTTOM_BUFFER) { lastPosition--; } if (setSelected) { mAdapter.setSelectedDay(mSelectedDay); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "GoTo position " + position); } // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position < firstPosition || position > lastPosition || forceScroll) { JalaliDate jDate = Jalali.gregorianToJalali(mTempTime); jDate.day = 1; mFirstDayOfMonth.set(Jalali.jalaliToGregorianTime(jDate)); mFirstDayOfMonth.normalize(true); setMonthDisplayed(mFirstDayOfMonth, jDate.month - 1, true); position = Utils.getWeeksSinceEpochFromJulianDay( Time.getJulianDay(Jalali.jalaliToGregorianTime(jDate).toMillis(true), mFirstDayOfMonth.gmtoff), mFirstDayOfWeek); mPreviousScrollState = OnScrollListener.SCROLL_STATE_FLING; if (animate) { mListView.smoothScrollToPositionFromTop(position, LIST_TOP_OFFSET, GOTO_SCROLL_DURATION); return true; } else { mListView.setSelectionFromTop(position, LIST_TOP_OFFSET); // Perform any after scroll operations that are needed onScrollStateChanged(mListView, OnScrollListener.SCROLL_STATE_IDLE); } } else if (setSelected) { // Otherwise just set the selection setMonthDisplayed(mSelectedDay, Jalali.gregorianToJalali(mSelectedDay).month - 1, true); } return false; }