Skip to content

Instantly share code, notes, and snippets.

Created August 5, 2014 19:01
Show Gist options
  • Save anonymous/14919b8d4a2a7b1e7efc to your computer and use it in GitHub Desktop.
Save anonymous/14919b8d4a2a7b1e7efc to your computer and use it in GitHub Desktop.
Create ForecastAdapter
package com.example.android.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ImageView;
/**
* {@link ForecastAdapter} exposes a list of weather forecasts
* from a {@link Cursor} to a {@link ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item_forecast, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Read weather icon ID from cursor
int weatherId = cursor.getInt(ForecastFragment.COL_WEATHER_ID);
// Use placeholder image for now
ImageView iconView = (ImageView) view.findViewById(R.id.list_item_icon);
iconView.setImageResource(R.drawable.ic_launcher);
// Read date from cursor
String dateString = cursor.getString(ForecastFragment.COL_WEATHER_DATE);
// Find TextView and set formatted date on it
TextView dateView = (TextView) view.findViewById(R.id.list_item_date_textview);
dateView.setText(Utility.getFriendlyDayString(context, dateString));
// Read weather forecast from cursor
String description = cursor.getString(ForecastFragment.COL_WEATHER_DESC);
// Find TextView and set weather forecast on it
TextView descriptionView = (TextView) view.findViewById(R.id.list_item_forecast_textview);
descriptionView.setText(description);
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
float high = cursor.getFloat(ForecastFragment.COL_WEATHER_MAX_TEMP);
// TODO: Find TextView and set formatted high temperature on it
// Read low temperature from cursor
float low = cursor.getFloat(ForecastFragment.COL_WEATHER_MIN_TEMP);
// TODO: Find TextView and set formatted low temperature on it
}
}
/** Required imports **/
import com.example.android.sunshine.app.data.WeatherContract;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
// Format used for storing dates in the database. ALso used for converting those strings
// back into date objects for comparison/processing.
public static final String DATE_FORMAT = "yyyyMMdd";
/**
* Helper method to convert the database representation of the date into something to display
* to users. As classy and polished a user experience as "20140102" is, we can do better.
*
* @param context Context to use for resource localization
* @param dateStr The db formatted date string, expected to be of the form specified
* in Utility.DATE_FORMAT
* @return a user-friendly representation of the date.
*/
public static String getFriendlyDayString(Context context, String dateStr) {
// The day string for forecast uses the following logic:
// For today: "Today, June 8"
// For tomorrow: "Tomorrow"
// For the next 5 days: "Wednesday" (just the day name)
// For all days after that: "Mon Jun 8"
Date todayDate = new Date();
String todayStr = WeatherContract.getDbDateString(todayDate);
Date inputDate = WeatherContract.getDateFromDb(dateStr);
// If the date we're building the String for is today's date, the format
// is "Today, June 24"
if (todayStr.equals(dateStr)) {
String today = context.getString(R.string.today);
return context.getString(
R.string.format_full_friendly_date,
today,
getFormattedMonthDay(context, dateStr));
} else {
Calendar cal = Calendar.getInstance();
cal.setTime(todayDate);
cal.add(Calendar.DATE, 7);
String weekFutureString = WeatherContract.getDbDateString(cal.getTime());
if (dateStr.compareTo(weekFutureString) < 0) {
// If the input date is less than a week in the future, just return the day name.
return getDayName(context, dateStr);
} else {
// Otherwise, use the form "Mon Jun 3"
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(inputDate);
}
}
}
/**
* Given a day, returns just the name to use for that day.
* E.g "today", "tomorrow", "wednesday".
*
* @param context Context to use for resource localization
* @param dateStr The db formatted date string, expected to be of the form specified
* in Utility.DATE_FORMAT
* @return
*/
public static String getDayName(Context context, String dateStr) {
SimpleDateFormat dbDateFormat = new SimpleDateFormat(Utility.DATE_FORMAT);
try {
Date inputDate = dbDateFormat.parse(dateStr);
Date todayDate = new Date();
// If the date is today, return the localized version of "Today" instead of the actual
// day name.
if (WeatherContract.getDbDateString(todayDate).equals(dateStr)) {
return context.getString(R.string.today);
} else {
// If the date is set for tomorrow, the format is "Tomorrow".
Calendar cal = Calendar.getInstance();
cal.setTime(todayDate);
cal.add(Calendar.DATE, 1);
Date tomorrowDate = cal.getTime();
if (WeatherContract.getDbDateString(tomorrowDate).equals(
dateStr)) {
return context.getString(R.string.tomorrow);
} else {
// Otherwise, the format is just the day of the week (e.g "Wednesday".
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
return dayFormat.format(inputDate);
}
}
} catch (ParseException e) {
e.printStackTrace();
// It couldn't process the date correctly.
return "";
}
}
/**
* Converts db date format to the format "Month day", e.g "June 24".
* @param context Context to use for resource localization
* @param dateStr The db formatted date string, expected to be of the form specified
* in Utility.DATE_FORMAT
* @return The day in the form of a string formatted "December 6"
*/
public static String getFormattedMonthDay(Context context, String dateStr) {
SimpleDateFormat dbDateFormat = new SimpleDateFormat(Utility.DATE_FORMAT);
try {
Date inputDate = dbDateFormat.parse(dateStr);
SimpleDateFormat monthDayFormat = new SimpleDateFormat("MMMM dd");
String monthDayString = monthDayFormat.format(inputDate);
return monthDayString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns true if metric unit should be used, or false if
* imperial units should be used.
*/
public static boolean isMetric(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(context.getString(R.string.pref_units_key),
context.getString(R.string.pref_units_metric)).equals(
context.getString(R.string.pref_units_metric));
}
<!-- Remember to set the root element of strings.xml to be <resources xmlns:xliff="http://schemas.android.com/apk/res-auto"> so it recognizes the xliff tags -->
<!-- Date label when displaying today's weather forecast [CHAR LIMIT=20] -->
<string name="today">Today</string>
<!-- Date label when displaying tomorrow's weather forecast [CHAR LIMIT=20] -->
<string name="tomorrow">Tomorrow</string>
<!-- Date format for displaying day of week and date (i.e. Mon Jun 1) [CHAR LIMIT=20] -->
<string name="format_full_friendly_date">
<xliff:g id="day_of_week">%1$s</xliff:g>, <xliff:g id="date">%2$s</xliff:g>
</string>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment