List of usage examples for android.database DatabaseUtils cursorRowToContentValues
public static void cursorRowToContentValues(Cursor cursor, ContentValues values)
From source file:com.example.android.sunshine.app.ui.ForecastFragment.java
private String[] getWeatherFromJson(Response<ApiResponse> response) { cVVector.addAll((Collection<? extends ContentValues>) response.body()); // 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);/*from w w w. j av a 2s. c o m*/ getContext().getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray); } String locationSetting = PreferenceUtils.getInstance(getActivity()) .getStringPreference(PreferenceKey.PREF_LOCATION_KEY); // 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 = getContext().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()); } String[] result = FetchWeatherUtils.convertContentValuesToUXFormat(getContext(), cVVector); return result; }
From source file:at.bitfire.ical4android.AndroidTaskList.java
protected AndroidTask[] queryTasks(String where, String[] whereArgs) throws CalendarStorageException { where = (where == null ? "" : "(" + where + ") AND ") + Tasks.LIST_ID + "=?"; whereArgs = ArrayUtils.add(whereArgs, String.valueOf(id)); @Cleanup/*from w ww. java 2 s. co m*/ Cursor cursor = null; try { cursor = provider.client.query(syncAdapterURI(provider.tasksUri()), taskBaseInfoColumns(), where, whereArgs, null); } catch (RemoteException e) { throw new CalendarStorageException("Couldn't query calendar events", e); } List<AndroidTask> tasks = new LinkedList<>(); while (cursor != null && cursor.moveToNext()) { ContentValues baseInfo = new ContentValues(cursor.getColumnCount()); DatabaseUtils.cursorRowToContentValues(cursor, baseInfo); tasks.add(taskFactory.newInstance(this, cursor.getLong(0), baseInfo)); } return tasks.toArray(taskFactory.newArray(tasks.size())); }
From source file:at.bitfire.ical4android.AndroidCalendar.java
protected AndroidEvent[] queryEvents(String where, String[] whereArgs) throws CalendarStorageException { where = (where == null ? "" : "(" + where + ") AND ") + Events.CALENDAR_ID + "=?"; whereArgs = ArrayUtils.add(whereArgs, String.valueOf(id)); @Cleanup//from w w w . j a va 2s .c o m Cursor cursor = null; try { cursor = provider.query(syncAdapterURI(Events.CONTENT_URI), eventBaseInfoColumns(), where, whereArgs, null); } catch (RemoteException e) { throw new CalendarStorageException("Couldn't query calendar events", e); } List<AndroidEvent> events = new LinkedList<>(); while (cursor != null && cursor.moveToNext()) { ContentValues baseInfo = new ContentValues(cursor.getColumnCount()); DatabaseUtils.cursorRowToContentValues(cursor, baseInfo); events.add(eventFactory.newInstance(this, cursor.getLong(0), baseInfo)); } return events.toArray(eventFactory.newArray(events.size())); }
From source file:com.example.danstormont.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 ww w. ja v a 2 s . c o m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; 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"; 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getDouble(OWM_COORD_LAT); double cityLongitude = coordJSON.getDouble(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); 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); // 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". dateTime = dayForecast.getLong(OWM_DATETIME); 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_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); 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); if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); } // Use a DEBUG variable to gate whether or not you do this, so you can easily // turn it on and off, and so that it's easy to see what you can rip out if // you ever want to remove it. if (DEBUG) { Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null); if (weatherCursor.moveToFirst()) { ContentValues resultValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues); Log.v(LOG_TAG, "Query succeeded! **********"); for (String key : resultValues.keySet()) { Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key)); } } else { Log.v(LOG_TAG, "Query failed! :( **********"); } } } }
From source file:org.most.persistence.DBAdapter.java
public List<ContentValues> getFIFOTuples(String table, int num) { Log.d(TAG, "Trying to get tuples from table " + table); if (open() == null) { Log.e(TAG, "Unable to open DB for getFIFOTuples"); logger.error("Unable to open DB for getFIFOTuples"); return new ArrayList<ContentValues>(); }/*w w w . ja v a 2 s. c o m*/ Cursor result = null; try { List<ContentValues> retVal = null; if (num <= 0) { result = _db.query(table, null, null, null, null, null, "_ID", null); retVal = new LinkedList<ContentValues>(); } else { result = _db.query(table, null, null, null, null, null, "_ID", num + ""); retVal = new ArrayList<ContentValues>(num); } ContentValues map; if (result.moveToFirst()) { do { map = new ContentValues(); DatabaseUtils.cursorRowToContentValues(result, map); retVal.add(map); } while (result.moveToNext()); } Log.d(TAG, "Got " + retVal.size() + "tuples from table " + table); return retVal; } catch (Exception e) { Log.e(TAG, "Exception in getFIFOTuples.", e); logger.error("Exception in getFIFOTuples.", e); return new ArrayList<ContentValues>(); } finally { try { result.close(); } catch (Exception e) { Log.e(TAG, "Exception closing cursor.", e); logger.error("Exception closing cursor.", e); } close(); } }
From source file:com.example.joel.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 a2s . com*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; 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"; // According to the video, this SHOULD be in a try-catch but that breaks other things... // This lesson is seriously messed up. 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); String[] resultStrs = new String[numDays]; 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); // 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". dateTime = dayForecast.getLong(OWM_DATETIME); 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_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); 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); String highAndLow = formatHighLows(high, low); String day = getReadableDateString(dateTime); resultStrs[i] = day + " - " + description + " - " + highAndLow; } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); // Use a DEBUG variable to gate whether or not you do this, so you can easily // turn it on and off, and so that it's easy to see what you can rip out if // you ever want to remove it. if (DEBUG) { Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null); if (weatherCursor.moveToFirst()) { ContentValues resultValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues); Log.v(LOG_TAG, "Query succeeded! **********"); for (String key : resultValues.keySet()) { Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key)); } } else { Log.v(LOG_TAG, "Query failed! :( **********"); } } } return resultStrs; }
From source file:com.udacity.movietimes.adapter.MovieDetailAdapter.java
public void updateFavoriteButton(final MovieViewHolder viewHolder, final Context context, final Cursor cursor) { // set the favorite button of the movie. First we check in the database if the favorite column // is Y or N. Based on that we switch the indicator as well as update the data in Movie DB. // Its basically act like a switch to update favorite column in the Movie Table Uri uri = MovieContract.MovieEntry.buildMovieWithMovieId(cursor.getLong(COL_ID)); Cursor temp = context.getContentResolver().query(uri, null, null, null, null, null); temp.moveToFirst();// www .j a v a 2s .c om final ContentValues values = new ContentValues(); DatabaseUtils.cursorRowToContentValues(temp, values); Typeface fontFamily = Typeface.createFromAsset(context.getAssets(), "fonts/fontawesome.ttf"); viewHolder.favorite.setTypeface(fontFamily); if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) { viewHolder.favorite.setText("\uf196"); } else { viewHolder.favorite.setText("\uf14a"); } viewHolder.favorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String movieId = (String) values.get(MovieContract.MovieEntry.COLUMN_MOVIE_ID); if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) { values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "Y"); viewHolder.favorite.setText("\uf14a"); } else { values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "N"); viewHolder.favorite.setText("\uf196"); } context.getContentResolver().update(MovieContract.MovieEntry.CONTENT_URI, values, MovieContract.MovieEntry.COLUMN_MOVIE_ID + " = ? ", new String[] { movieId }); } }); }
From source file:com.example.conor.dotaapp.FetchMatchTask.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 void getMatchDataFromJson(String matchJsonStr, String steamId) throws JSONException { //LOG TAGS final String LOG_TAG = FetchMatchTask.class.getSimpleName(); //final String LOG_MATCH_JSON = "Match JSON Object"; final String LOG_MATCH_ARRAY = "Match JSON Array"; //JSON strings final String OWM_MATCHES = "matches"; final String OWM_MATCHID = "match_id"; final String OWM_START = "start_time"; final String OWM_PLAYERS = "players"; //final String OWM_PLAYERID = "account_id"; //final String OWM_HEROID = "hero_id"; final String OWM_RESULT = "result"; //Get number of matches to display from settings SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); String numberOfMatches = sharedPrefs.getString(mContext.getString(R.string.num_matches_key), mContext.getString(R.string.num_matches_default)); int numMatches = Integer.parseInt(numberOfMatches); try { JSONObject matchJson = new JSONObject(matchJsonStr); JSONArray matchArray = matchJson.getJSONObject(OWM_RESULT).getJSONArray(OWM_MATCHES); Log.v(LOG_MATCH_ARRAY, "matchArray: " + matchArray); Vector<ContentValues> cVVector = new Vector<ContentValues>(matchArray.length()); //String array to hold results of each match String[] resultStrs = new String[numMatches]; //For loop to loop through all matches //ATM: matchArray.length() = 5 for (int i = 0; i < matchArray.length(); i++) { // For now, using the format "Date, hero, match_id" String hero, match_id, dateTime; long date; // Get the JSON object representing a single match JSONObject singleMatch = matchArray.getJSONObject(i); Log.v(LOG_TAG, "Single Match JSONObject: " + singleMatch); //Get match_id of a single match match_id = singleMatch.getString(OWM_MATCHID); Log.v(LOG_TAG, "match_id: " + match_id); //Change date from UTC to readable date. Get Long value first date = Long.parseLong(singleMatch.getString(OWM_START)); //Output actual date instead of just seconds for start_time dateTime = getReadableDateString(date); /** * rest of JSON code is for match data * */ //Array of players JSONArray allPlayers = matchArray.getJSONObject(i).getJSONArray(OWM_PLAYERS); Log.v(LOG_TAG, "allPlayers JSONArray: " + allPlayers); //Returns single Hero Object with JSONObject heroObject = singleMatch.getJSONArray(OWM_PLAYERS).getJSONObject(0); Log.v(LOG_TAG, "heroObject: " + heroObject); hero = heroObject.getString("hero_id"); Log.v(LOG_TAG, "Hero ID: " + hero); for (int j = 0; j < allPlayers.length(); j++) { JSONObject singlePlayer = allPlayers.getJSONObject(j); } //Add strings to resultStrs at index i resultStrs[i] = "Date: " + dateTime + ", Hero: " + hero + ", Match ID: " + match_id; Log.v(LOG_TAG, "ResultStrs[" + i + "]: " + resultStrs[i]); for (Object s : resultStrs) { Log.v(LOG_TAG, "Dota Data to Display: " + s); } /** * END OF JSON DATA */ //Insert data into match table ContentValues matchValues = new ContentValues(); matchValues.put(MatchEntry.COLUMN_MATCH_KEY, match_id); matchValues.put(MatchEntry.COLUMN_START_TIME, dateTime); matchValues.put(MatchEntry.COLUMN_P_ACCOUNT_ID, steamId); cVVector.add(matchValues); } int inserted = 0; // add to database using bulkInsert if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(MatchEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = MatchEntry.COLUMN_START_TIME + " ASC"; Uri matchForPlayerUri = MatchEntry.buildMatchPlayerWithStartTime(steamId, System.currentTimeMillis()); //display bulk insert Cursor cur = mContext.getContentResolver().query(matchForPlayerUri, null, null, null, sortOrder); //Display cursor ////NULL CURSOR Log.e(LOG_TAG, "Cursor: " + cur); 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, "FetchMatchTask Complete. " + inserted + " Inserted"); //String[] resultStrsActual = convertContentValuesToUXFormat(cVVector); //return resultStrsActual; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } //return null; }
From source file:com.jimandreas.popularmovies.MovieDetailFragment.java
@Nullable @Override/* ww w . jav a 2 s . c o m*/ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments(); if (arguments != null) { mUri = arguments.getParcelable(MovieDetailFragment.DETAIL_URI); } View rootView = inflater.inflate(R.layout.fragment_detail, container, false); /* * Yes yes my master, we have the Precious handle to the Layout!! * * NOTE: now obsolete - moved to the Constraint system for layout */ // mTheMasterGridLayout = (GridLayout) rootView.findViewById(R.id.movie_detail_grid_layout); // mTheMasterGridLayout = (ConstraintLayout) // rootView.findViewById(R.id.movie_detail_grid_layout); mMDSynopsis = (TextView) rootView.findViewById(R.id.movie_detail_synopsis); mMDTitleView = (TextView) rootView.findViewById(R.id.movie_detail_title); mMDPosterView = (ImageView) rootView.findViewById(R.id.movie_detail_poster_image); mMDYear = (TextView) rootView.findViewById(R.id.movie_detail_year); mMDRunningtime = (TextView) rootView.findViewById(R.id.movie_detail_runningtime); mMDRatingAndVotes = (TextView) rootView.findViewById(R.id.movie_detail_rating_and_votes); mMDSynopsis = (TextView) rootView.findViewById(R.id.movie_detail_synopsis); mMDLoadProgress = (ProgressBar) rootView.findViewById(R.id.movie_detail_progress_circle); // cache up all the Trailer and Review UX views - // these will get toggled into visibility based on their // rather random presence in TheMovieDB... mMDTrailers = (TextView) rootView.findViewById(R.id.movie_detail_trailers); mMDPlay1 = (ImageView) rootView.findViewById(R.id.movie_detail_trailer_play_button); mMDPlay2 = (ImageView) rootView.findViewById(R.id.movie_detail_trailer_play_button2); mMDPlay3 = (ImageView) rootView.findViewById(R.id.movie_detail_trailer_play_button3); mMDTrailer1 = (TextView) rootView.findViewById(R.id.movie_detail_trailer1); mMDTrailer2 = (TextView) rootView.findViewById(R.id.movie_detail_trailer2); mMDTrailer3 = (TextView) rootView.findViewById(R.id.movie_detail_trailer3); mMDTrailer1.setOnClickListener(mTrailerClickListener); mMDTrailer2.setOnClickListener(mTrailerClickListener); mMDTrailer3.setOnClickListener(mTrailerClickListener); mMDReviews = (TextView) rootView.findViewById(R.id.movie_detail_reviews); mMDRev1 = (ImageView) rootView.findViewById(R.id.play_rev1); mMDRev2 = (ImageView) rootView.findViewById(R.id.play_rev2); mMDRev3 = (ImageView) rootView.findViewById(R.id.play_rev3); mMovieReview1 = (TextView) rootView.findViewById(R.id.movie_review1); mMovieReview2 = (TextView) rootView.findViewById(R.id.movie_review2); mMovieReview3 = (TextView) rootView.findViewById(R.id.movie_review3); mMovieReview1.setOnClickListener(mReviewClickListener); mMovieReview2.setOnClickListener(mReviewClickListener); mMovieReview3.setOnClickListener(mReviewClickListener); mMDFavoriteButton = (ImageView) rootView.findViewById(R.id.movie_detail_favorite_imageviewbutton); mMDFavoriteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int favorite_state; // Snackbar.make(v, "clicky", Snackbar.LENGTH_SHORT) // .setAction("Action", null).show(); if (mCursor == null || !mCursor.moveToFirst()) { return; } // pull the favorite table entry if it exists int movie_id = mCursor.getInt(COL_MOVIE_ID); Uri uri = MovieFavorites.buildMovieDetailsUri(movie_id); Cursor fav_cursor = getContext().getContentResolver().query(uri, null, null, null, null); // debugging ContentValues testValues = new ContentValues(); if (fav_cursor.moveToFirst()) { DatabaseUtils.cursorRowToContentValues(fav_cursor, testValues); } // dump in the current movie table entry into the new // favorite row info ContentValues favoriteValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(mCursor, favoriteValues); // OK if the favorite row already exists, then toggle its state // otherwise set it to "1" or true - it IS a favorite now int fav_status = 0; if (fav_cursor.moveToFirst()) { fav_status = fav_cursor.getInt(COL_FAVORITE); } favoriteValues.put(MovieFavorites.COLUMN_MYNAME, "favorites"); if (fav_status == 0) { favorite_state = 1; favoriteValues.remove(MovieFavorites.COLUMN_FAVORITE); favoriteValues.put(MovieFavorites.COLUMN_FAVORITE, 1); favoriteValues.put(MovieFavorites.COLUMN_FAVORITE_TIMESTAMP, mCalendar.getTimeInMillis()); Timber.i("favorites - added " + movie_id + " to favorites"); } else { favorite_state = 0; favoriteValues.remove(MovieFavorites.COLUMN_FAVORITE); favoriteValues.put(MovieFavorites.COLUMN_FAVORITE, 0); Timber.i("favorites - removed " + movie_id + " from favorites"); } /* * stuff this favorite row into the favorites table * but first remove the _id key or sqlite will crash */ favoriteValues.remove("_id"); Uri updated = getContext().getContentResolver().insert(MovieFavorites.CONTENT_URI, favoriteValues); ContentValues movieValues = new ContentValues(); if (favorite_state == 1) { mMDFavoriteButton.setImageResource(R.drawable.ic_favorite_selected); movieValues.put(MoviePopular.COLUMN_FAVORITE, 1); mTM.addFavoriteID(movie_id); } else { mMDFavoriteButton.setImageResource(R.drawable.ic_favorite_unselected); movieValues.put(MoviePopular.COLUMN_FAVORITE, 0); mTM.removeFavoriteID(movie_id); } /* * do an update selecting on the movie_id in BOTH popular and top_rated * tables. The same movie_id might be in both tables. */ String myMode = MoviePopular.getMovieModeFromUri(mUri); int result; uri = MoviePopular.buildMovieDetailsUri(movie_id); result = getContext().getContentResolver().update(uri, movieValues, MoviePopular.COLUMN_MOVIE_ID + " = " + String.valueOf(movie_id), null); uri = MovieTopRated.buildMovieDetailsUri(movie_id); result = getContext().getContentResolver().update(uri, movieValues, MoviePopular.COLUMN_MOVIE_ID + " = " + String.valueOf(movie_id), null); } }); mTM = TrafficManager.getInstance(getContext()); return rootView; }
From source file:com.example.asaldanha.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 ww .j a va 2 s. c om */ // private String[] getWeatherDataFromJson(String forecastJsonStr, 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); } // 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()); } 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; }