List of usage examples for android.database DatabaseUtils cursorRowToContentValues
public static void cursorRowToContentValues(Cursor cursor, ContentValues values)
From source file:com.task.krabiysok.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.//from w w w . j a v a 2 s. 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); } // add to database if (cVVector.size() > 0) { ContentValues[] array = new ContentValues[cVVector.size()]; cVVector.toArray(array); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, array); } // 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:br.com.scalasoft.alvaro.weather.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 ava 2 s . 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); } // add to database if (cVVector.size() > 0) { 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()); } 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:net.theroberson.sunshineapp.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 ww w . j a va 2s . com */ 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); } // add to database if (cVVector.size() > 0) { 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()); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); //String[] resultStrs = convertContentValuesToUXFormat(cVVector); //return resultStrs; return convertContentValuesToUXFormat(cVVector); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.adapter.MovieDetailsAdapter.java
/** * Method to check if movie is favorite. * * @param movieId to check./*from w w w. java 2 s. co m*/ * @return movie title after addition else null */ private String addToFavorites(int movieId) { String title = null; String[] projection = new String[] { "*" }; String selection = MovieEntry.C_MOVIE_ID + "=?"; String[] selectionArgs = { String.valueOf(movieId) }; ContentResolver contentResolver = mContext.getContentResolver(); Cursor cMovies = null; Cursor cTrailers = null; Cursor cReviews = null; try { cMovies = contentResolver.query(MovieEntry.CONTENT_URI, projection, selection, selectionArgs, null); if (null != cMovies && cMovies.moveToFirst()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cMovies, contentValues); contentValues.remove("_id"); title = contentValues.getAsString(MovieEntry.C_ORIGINAL_TITLE); contentResolver.insert(MovieEntry.FAVORITES_CONTENT_URI, contentValues); } cTrailers = contentResolver.query(TrailersEntry.CONTENT_URI, projection, selection, selectionArgs, null); while (null != cTrailers && cTrailers.moveToNext()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cTrailers, contentValues); contentValues.remove("_id"); contentResolver.insert(TrailersEntry.FAVORITES_CONTENT_URI, contentValues); } cReviews = contentResolver.query(ReviewsEntry.CONTENT_URI, projection, selection, selectionArgs, null); while (null != cReviews && cReviews.moveToNext()) { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cReviews, contentValues); contentValues.remove("_id"); contentResolver.insert(ReviewsEntry.FAVORITES_CONTENT_URI, contentValues); } } catch (SQLException e) { Log.e(LOG_TAG, "SQLException!"); } finally { if (null != cMovies) cMovies.close(); if (null != cTrailers) cTrailers.close(); if (null != cReviews) cReviews.close(); } return title; }
From source file:com.example.sunshine.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 .ja v a 2 s .c om*/ */ 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); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cVal = new ContentValues[cVVector.size()]; cVVector.toArray(cVal); mContext.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cVal); } // 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.krishnateja.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.//from w w w . ja v a 2 s.com */ 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(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherContract.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.iyedb.sunshine.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { Log.d(LOG_TAG, "in doInBackground"); // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }//from ww w.ja v a2 s .c o m String locationParam = params[0]; Log.d(LOG_TAG, "getting weather data for " + locationParam); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { getWeatherDataFromJson(forecastJsonStr, numDays, locationParam); if (DEBUG) { Cursor cursor = mContext .getContentResolver().query( WeatherEntry.CONTENT_URI, new String[] { WeatherEntry._ID, WeatherEntry.COLUMN_LOC_KEY, WeatherEntry.COLUMN_WEATHER_ID }, null, null, null); Log.d(LOG_TAG, "Weather table contents:"); while (cursor.moveToNext()) { ContentValues resultValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cursor, resultValues); StringBuilder stringBuilder = new StringBuilder(); for (String key : resultValues.keySet()) { stringBuilder.append(key).append(':').append(resultValues.getAsString(key)).append('|'); } Log.v(LOG_TAG, stringBuilder.toString()); } Cursor cursorLoc = mContext.getContentResolver() .query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID, LocationEntry.COLUMN_LOCATION_SETTING, LocationEntry.COLUMN_CITY_NAME }, null, null, null); Log.d(LOG_TAG, "Location table contents:"); while (cursorLoc.moveToNext()) { ContentValues resultValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cursorLoc, resultValues); StringBuilder stringBuilder = new StringBuilder(); for (String key : resultValues.keySet()) { stringBuilder.append(key).append(':').append(resultValues.getAsString(key)).append('|'); } Log.v(LOG_TAG, stringBuilder.toString()); } } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; }
From source file:com.example.jumpnote.android.SyncAdapter.java
public List<ModelJava.Note> getLocallyChangedNotes(ContentProviderClient provider, Account account, Date sinceDate) throws RemoteException { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Getting local notes changed since " + Long.toString(sinceDate.getTime())); }//ww w .ja v a 2 s . co m Cursor notesCursor = provider.query(JumpNoteContract.buildNoteListUri(account.name), PROJECTION, JumpNoteContract.Notes.MODIFIED_DATE + " > ?", new String[] { Long.toString(sinceDate.getTime()) }, null); List<ModelJava.Note> locallyChangedNotes = new ArrayList<ModelJava.Note>(); while (notesCursor.moveToNext()) { ContentValues values = new ContentValues(); DatabaseUtils.cursorRowToContentValues(notesCursor, values); ModelJava.Note changedNote = new ModelJava.Note(values); locallyChangedNotes.add(changedNote); } notesCursor.close(); return locallyChangedNotes; }
From source file:com.samsung.android.remindme.SyncAdapter.java
public List<ModelJava.Alert> getLocallyChangedAlerts(ContentProviderClient provider, Account account, Date sinceDate) throws RemoteException { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Getting local alerts changed since " + Long.toString(sinceDate.getTime())); }/*from w w w .ja va2 s . c om*/ Cursor alertsCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION, RemindMeContract.Alerts.MODIFIED_DATE + " > ?", new String[] { Long.toString(sinceDate.getTime()) }, null); List<ModelJava.Alert> locallyChangedAlerts = new ArrayList<ModelJava.Alert>(); while (alertsCursor.moveToNext()) { ContentValues values = new ContentValues(); DatabaseUtils.cursorRowToContentValues(alertsCursor, values); ModelJava.Alert changedAlert = new ModelJava.Alert(values); locallyChangedAlerts.add(changedAlert); } alertsCursor.close(); return locallyChangedAlerts; }
From source file:org.wheelmap.android.fragment.POIDetailFragment.java
public void load(Cursor c) { mCursor = c;//from w w w. j a v a 2 s .c o m if (c == null || c.getCount() < 1 || getPoiId() == -1) { titlebarBackbutton.setVisibility(View.GONE); addressTitle.setVisibility(View.GONE); addressText.setVisibility(View.GONE); commentText.setVisibility(View.GONE); commentTitle.setVisibility(View.GONE); buttonTangoMeasure.setVisibility(View.GONE); buttonPhoto.setVisibility(View.GONE); buttonEdit.setVisibility(View.GONE); buttonRoute.setVisibility(View.GONE); buttonShare.setVisibility(View.GONE); nameText.setVisibility(View.GONE); categoryText.setVisibility(View.GONE); accessStateText.setVisibility(View.GONE); accessStateLayout.setVisibility(View.GONE); toiletStateText.setVisibility(View.GONE); toiletStateLayout.setVisibility(View.GONE); webText.setVisibility(View.GONE); phoneText.setVisibility(View.GONE); photoTitle.setVisibility(View.GONE); photoLayout.setVisibility(View.GONE); noCommentText.setVisibility(View.GONE); noAdressText.setVisibility(View.GONE); noPhotosText.setVisibility(View.GONE); nothing.setVisibility(View.VISIBLE); return; } else { c.moveToFirst(); if (getActivity() != null && getActivity().getApplication() != null) if (!UtilsMisc.isTablet(getActivity().getApplication())) { mCrrLongitude = POIHelper.getLongitude(c); mCrrLatitude = POIHelper.getLatitude(c); org.osmdroid.util.GeoPoint geoPoint = new org.osmdroid.util.GeoPoint(mCrrLatitude, mCrrLongitude); if (mMapView != null) { centerMap(geoPoint, true); } } titlebarBackbutton.setVisibility(View.VISIBLE); addressTitle.setVisibility(View.VISIBLE); addressText.setVisibility(View.VISIBLE); commentText.setVisibility(View.VISIBLE); commentTitle.setVisibility(View.VISIBLE); if (TangoUtils.isTangoSupported()) { buttonTangoMeasure.setVisibility(View.VISIBLE); } else { buttonTangoMeasure.setVisibility(View.GONE); } buttonPhoto.setVisibility(View.VISIBLE); buttonEdit.setVisibility(View.VISIBLE); buttonRoute.setVisibility(View.VISIBLE); buttonShare.setVisibility(View.VISIBLE); nameText.setVisibility(View.VISIBLE); categoryText.setVisibility(View.VISIBLE); accessStateText.setVisibility(View.VISIBLE); accessStateLayout.setVisibility(View.VISIBLE); toiletStateText.setVisibility(View.VISIBLE); toiletStateLayout.setVisibility(View.VISIBLE); webText.setVisibility(View.VISIBLE); phoneText.setVisibility(View.VISIBLE); photoTitle.setVisibility(View.VISIBLE); photoLayout.setVisibility(View.VISIBLE); nothing.setVisibility(View.GONE); poiId = POIHelper.getId(c); String wmIdString = POIHelper.getWMId(c); WheelchairFilterState accessState = POIHelper.getWheelchair(c); WheelchairFilterState toiletState = POIHelper.getWheelchairToilet(c); if (accessState == WheelchairFilterState.NO_PREFERENCE) { accessState = WheelchairFilterState.UNKNOWN; } if (toiletState == WheelchairFilterState.NO_PREFERENCE) { toiletState = WheelchairFilterState.TOILET_UNKNOWN; } String name = POIHelper.getName(c); String comment = POIHelper.getComment(c); String website = POIHelper.getWebsite(c); String phone = POIHelper.getPhone(c); String street = POIHelper.getStreet(c); String houseNum = POIHelper.getHouseNumber(c); String postCode = POIHelper.getPostcode(c); String city = POIHelper.getCity(c); String address = ""; if (street != null) { address += street + " "; } if (houseNum != null) { address += houseNum + " "; } if (postCode != null) { address += "\n"; address += postCode + " "; } if (city != null) { address += city + " "; } int checkIfAdress = 3; if (address == "") { addressText.setVisibility(View.GONE); checkIfAdress--; } else { addressText.setVisibility(View.VISIBLE); addressText.setText(address); } if (phone != null) { phoneText.setVisibility(View.VISIBLE); phoneText.setText(phone); } else { phoneText.setVisibility(View.GONE); checkIfAdress--; } if (website != null) { webText.setVisibility(View.VISIBLE); webText.setClickable(true); String text = "<a href=" + website + ">" + website + "</a>"; webText.setText(Html.fromHtml(text)); webText.setMovementMethod(LinkMovementMethod.getInstance()); } else { webText.setVisibility(View.GONE); checkIfAdress--; } if (checkIfAdress == 0) noAdressText.setVisibility(View.VISIBLE); else noAdressText.setVisibility(View.GONE); if (comment == null) { commentText.setVisibility(View.GONE); noCommentText.setVisibility(View.VISIBLE); } else { commentText.setVisibility(View.VISIBLE); noCommentText.setVisibility(View.GONE); } final double latitude = POIHelper.getLatitude(c); final double longitude = POIHelper.getLongitude(c); int nodeTypeId = POIHelper.getNodeTypeId(c); int categoryId = POIHelper.getCategoryId(c); SupportManager sm = WheelmapApp.getSupportManager(); NodeType nodeType = sm.lookupNodeType(nodeTypeId); accessStateLayout.setVisibility(View.VISIBLE); setWheelchairAccessState(accessState); toiletStateLayout.setVisibility(View.VISIBLE); setWheelchairToiletState(toiletState); if (name != null && name.length() > 0) { nameText.setText(name); } else { nameText.setText(nodeType.localizedName); } String category = sm.lookupCategory(categoryId).localizedName; categoryText.setText(category); commentText.setText(comment); fillDirectionsActionProvider(latitude, longitude, street, houseNum, postCode, city); fillShareActionProvider(wmIdString, name, nodeType.localizedName, comment, address); mShowMenu = true; getActivity().invalidateOptionsMenu(); poiValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(c, poiValues); } }