Created
July 2, 2016 16:23
-
-
Save quintinmarcelino/15e449121589f85a34954aec2ebee2bf to your computer and use it in GitHub Desktop.
Lists and Adapters Treehouse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.ui; | |
import android.app.AlertDialog; | |
import android.app.Dialog; | |
import android.app.DialogFragment; | |
import android.content.Context; | |
import android.os.Bundle; | |
import teamtreehouse.com.stormy.R; | |
/** | |
* Created by benjakuben on 12/3/14. | |
*/ | |
public class AlertDialogFragment extends DialogFragment { | |
@Override | |
public Dialog onCreateDialog(Bundle savedInstanceState) { | |
Context context = getActivity(); | |
AlertDialog.Builder builder = new AlertDialog.Builder(context) | |
.setTitle(context.getString(R.string.error_title)) | |
.setMessage(context.getString(R.string.error_message)) | |
.setPositiveButton(context.getString(R.string.error_ok_button_text), null); | |
AlertDialog dialog = builder.create(); | |
return dialog; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.weather; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.TimeZone; | |
import teamtreehouse.com.stormy.R; | |
/** | |
* Created by benjakuben on 12/8/14. | |
*/ | |
public class Current { | |
private String mIcon; | |
private long mTime; | |
private double mTemperature; | |
private double mHumidity; | |
private double mPrecipChance; | |
private String mSummary; | |
private String mTimeZone; | |
public String getTimeZone() { | |
return mTimeZone; | |
} | |
public void setTimeZone(String timeZone) { | |
mTimeZone = timeZone; | |
} | |
public String getIcon() { | |
return mIcon; | |
} | |
public void setIcon(String icon) { | |
mIcon = icon; | |
} | |
public int getIconId() { | |
return Forecast.getIconId(mIcon); | |
} | |
public long getTime() { | |
return mTime; | |
} | |
public String getFormattedTime() { | |
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); | |
formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); | |
Date dateTime = new Date(getTime() * 1000); | |
String timeString = formatter.format(dateTime); | |
return timeString; | |
} | |
public void setTime(long time) { | |
mTime = time; | |
} | |
public int getTemperature() { | |
return (int)Math.round(mTemperature); | |
} | |
public void setTemperature(double temperature) { | |
mTemperature = temperature; | |
} | |
public double getHumidity() { | |
return mHumidity; | |
} | |
public void setHumidity(double humidity) { | |
mHumidity = humidity; | |
} | |
public int getPrecipChance() { | |
double precipPercentage = mPrecipChance * 100; | |
return (int)Math.round(precipPercentage); | |
} | |
public void setPrecipChance(double precipChance) { | |
mPrecipChance = precipChance; | |
} | |
public String getSummary() { | |
return mSummary; | |
} | |
public void setSummary(String summary) { | |
mSummary = summary; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.ui; | |
import android.app.ListActivity; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.os.Parcelable; | |
import android.support.v7.app.ActionBarActivity; | |
import android.widget.ArrayAdapter; | |
import java.util.Arrays; | |
import teamtreehouse.com.stormy.R; | |
import teamtreehouse.com.stormy.adapters.DayAdapter; | |
import teamtreehouse.com.stormy.weather.Day; | |
public class DailyForecastActivity extends ListActivity { | |
private Day[] mDays; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_daily_forecast); | |
Intent intent = getIntent(); | |
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST); | |
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class); | |
DayAdapter adapter = new DayAdapter(this, mDays); | |
setListAdapter(adapter); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.weather; | |
import android.os.Parcel; | |
import android.os.Parcelable; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.TimeZone; | |
/** | |
* Created by benjakuben on 2/5/15. | |
*/ | |
public class Day implements Parcelable { | |
private long mTime; | |
private String mSummary; | |
private double mTemperatureMax; | |
private String mIcon; | |
private String mTimezone; | |
public void setTime(long time) { | |
mTime = time; | |
} | |
public String getSummary() { | |
return mSummary; | |
} | |
public void setSummary(String summary) { | |
mSummary = summary; | |
} | |
public double getTemperatureMax() { | |
return (int)Math.round(mTemperatureMax); | |
} | |
public void setTemperatureMax(double temperatureMax) { | |
mTemperatureMax = temperatureMax; | |
} | |
public String getIcon() { | |
return mIcon; | |
} | |
public void setIcon(String icon) { | |
mIcon = icon; | |
} | |
public String getTimezone() { | |
return mTimezone; | |
} | |
public void setTimezone(String timezone) { | |
mTimezone = timezone; | |
} | |
public int getIconId() { | |
return Forecast.getIconId(mIcon); | |
} | |
public String getDayOfTheWeek() { | |
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); | |
formatter.setTimeZone(TimeZone.getTimeZone(mTimezone)); | |
Date dateTime = new Date(mTime * 1000); | |
return formatter.format(dateTime); | |
} | |
@Override | |
public int describeContents() { | |
return 0; | |
} | |
@Override | |
public void writeToParcel(Parcel dest, int flags) { | |
dest.writeLong(mTime); | |
dest.writeString(mSummary); | |
dest.writeDouble(mTemperatureMax); | |
dest.writeString(mIcon); | |
dest.writeString(mTimezone); | |
} | |
private Day(Parcel in) { | |
mTime = in.readLong(); | |
mSummary = in.readString(); | |
mTemperatureMax = in.readDouble(); | |
mIcon = in.readString(); | |
mTimezone = in.readString(); | |
} | |
public Day() { } | |
public static final Creator<Day> CREATOR = new Creator<Day>() { | |
@Override | |
public Day createFromParcel(Parcel source) { | |
return new Day(source); | |
} | |
@Override | |
public Day[] newArray(int size) { | |
return new Day[size]; | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.adapters; | |
import android.content.Context; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.BaseAdapter; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import teamtreehouse.com.stormy.R; | |
import teamtreehouse.com.stormy.weather.Day; | |
/** | |
* Created by Quintin on 6/24/2016. | |
*/ | |
public class DayAdapter extends BaseAdapter { | |
private Context mContext; | |
private Day[] mDays; | |
public DayAdapter(Context context, Day[] days) { | |
mContext = context; | |
//mDays = new Day[days.length]; | |
mDays = days; | |
} | |
@Override | |
public int getCount() { | |
return mDays.length; | |
} | |
@Override | |
public Object getItem(int position) { | |
return mDays[position]; | |
} | |
@Override | |
public long getItemId(int position) { | |
return 0; //We aren't using this, but it can be used to tag items for easy reference | |
} | |
@Override | |
public View getView(int position, View convertView, ViewGroup parent) { | |
ViewHolder holder; | |
if (convertView == null) { | |
//brand new | |
convertView = LayoutInflater.from(mContext).inflate(R.layout.daily_list_item, null); | |
holder = new ViewHolder(); | |
holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView); | |
holder.temperatureLabel = (TextView) convertView.findViewById(R.id.temperatureLabel); | |
convertView.setTag(holder); | |
} | |
else { | |
holder = (ViewHolder) convertView.getTag(); | |
} | |
Day day = mDays[position]; | |
holder.iconImageView.setImageResource(day.getIconId()); | |
holder.temperatureLabel.setText(day.getTemperatureMax() + ""); | |
holder.dayLabel.setText(day.getDayOfTheWeek()); | |
return convertView; | |
} | |
private static class ViewHolder { | |
ImageView iconImageView; //public by default | |
TextView temperatureLabel; | |
TextView dayLabel; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.weather; | |
import teamtreehouse.com.stormy.R; | |
/** | |
* Created by benjakuben on 2/5/15. | |
*/ | |
public class Forecast { | |
private Current mCurrent; | |
private Hour[] mHourlyForecast; | |
private Day[] mDailyForecast; | |
public Current getCurrent() { | |
return mCurrent; | |
} | |
public void setCurrent(Current current) { | |
mCurrent = current; | |
} | |
public Hour[] getHourlyForecast() { | |
return mHourlyForecast; | |
} | |
public void setHourlyForecast(Hour[] hourlyForecast) { | |
mHourlyForecast = hourlyForecast; | |
} | |
public Day[] getDailyForecast() { | |
return mDailyForecast; | |
} | |
public void setDailyForecast(Day[] dailyForecast) { | |
mDailyForecast = dailyForecast; | |
} | |
public static int getIconId(String iconString) { | |
// clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night. | |
int iconId = R.drawable.clear_day; | |
if (iconString.equals("clear-day")) { | |
iconId = R.drawable.clear_day; | |
} | |
else if (iconString.equals("clear-night")) { | |
iconId = R.drawable.clear_night; | |
} | |
else if (iconString.equals("rain")) { | |
iconId = R.drawable.rain; | |
} | |
else if (iconString.equals("snow")) { | |
iconId = R.drawable.snow; | |
} | |
else if (iconString.equals("sleet")) { | |
iconId = R.drawable.sleet; | |
} | |
else if (iconString.equals("wind")) { | |
iconId = R.drawable.wind; | |
} | |
else if (iconString.equals("fog")) { | |
iconId = R.drawable.fog; | |
} | |
else if (iconString.equals("cloudy")) { | |
iconId = R.drawable.cloudy; | |
} | |
else if (iconString.equals("partly-cloudy-day")) { | |
iconId = R.drawable.partly_cloudy; | |
} | |
else if (iconString.equals("partly-cloudy-night")) { | |
iconId = R.drawable.cloudy_night; | |
} | |
return iconId; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.weather; | |
/** | |
* Created by benjakuben on 2/5/15. | |
*/ | |
public class Hour { | |
private long mTime; | |
private String mSummary; | |
private double mTemperature; | |
private String mIcon; | |
private String mTimezone; | |
public long getTime() { | |
return mTime; | |
} | |
public void setTime(long time) { | |
mTime = time; | |
} | |
public String getSummary() { | |
return mSummary; | |
} | |
public void setSummary(String summary) { | |
mSummary = summary; | |
} | |
public double getTemperature() { | |
return mTemperature; | |
} | |
public void setTemperature(double temperature) { | |
mTemperature = temperature; | |
} | |
public String getIcon() { | |
return mIcon; | |
} | |
public void setIcon(String icon) { | |
mIcon = icon; | |
} | |
public String getTimezone() { | |
return mTimezone; | |
} | |
public void setTimezone(String timezone) { | |
mTimezone = timezone; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package teamtreehouse.com.stormy.ui; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.graphics.drawable.Drawable; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.Bundle; | |
import android.support.v7.app.ActionBarActivity; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.ImageView; | |
import android.widget.ProgressBar; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.squareup.okhttp.Call; | |
import com.squareup.okhttp.Callback; | |
import com.squareup.okhttp.OkHttpClient; | |
import com.squareup.okhttp.Request; | |
import com.squareup.okhttp.Response; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.IOException; | |
import java.util.jar.JarException; | |
import butterknife.ButterKnife; | |
import butterknife.InjectView; | |
import butterknife.OnClick; | |
import teamtreehouse.com.stormy.R; | |
import teamtreehouse.com.stormy.weather.Current; | |
import teamtreehouse.com.stormy.weather.Day; | |
import teamtreehouse.com.stormy.weather.Forecast; | |
import teamtreehouse.com.stormy.weather.Hour; | |
public class MainActivity extends ActionBarActivity { | |
public static final String TAG = MainActivity.class.getSimpleName(); | |
public static final String DAILY_FORECAST = "DAILY_FORECAST"; | |
private Forecast mForecast; | |
@InjectView(R.id.timeLabel) TextView mTimeLabel; | |
@InjectView(R.id.temperatureLabel) TextView mTemperatureLabel; | |
@InjectView(R.id.humidityValue) TextView mHumidityValue; | |
@InjectView(R.id.precipValue) TextView mPrecipValue; | |
@InjectView(R.id.summaryLabel) TextView mSummaryLabel; | |
@InjectView(R.id.iconImageView) ImageView mIconImageView; | |
@InjectView(R.id.refreshImageView) ImageView mRefreshImageView; | |
@InjectView(R.id.progressBar) ProgressBar mProgressBar; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
ButterKnife.inject(this); | |
mProgressBar.setVisibility(View.INVISIBLE); | |
final double latitude = 42.3876; | |
final double longitude = -71.0995; | |
mRefreshImageView.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
getForecast(latitude, longitude); | |
} | |
}); | |
getForecast(latitude, longitude); | |
Log.d(TAG, "Main UI code is running!"); | |
} | |
private void getForecast(double latitude, double longitude) { | |
String apiKey = "d2fd58d75b2c25aa8f464fc723c028a2"; | |
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + | |
"/" + latitude + "," + longitude; | |
if (isNetworkAvailable()) { | |
toggleRefresh(); | |
OkHttpClient client = new OkHttpClient(); | |
Request request = new Request.Builder() | |
.url(forecastUrl) | |
.build(); | |
Call call = client.newCall(request); | |
call.enqueue(new Callback() { | |
@Override | |
public void onFailure(Request request, IOException e) { | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
toggleRefresh(); | |
} | |
}); | |
alertUserAboutError(); | |
} | |
@Override | |
public void onResponse(Response response) throws IOException { | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
toggleRefresh(); | |
} | |
}); | |
try { | |
String jsonData = response.body().string(); | |
Log.v(TAG, jsonData); | |
if (response.isSuccessful()) { | |
mForecast = parseForecastDetails(jsonData); | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
updateDisplay(); | |
} | |
}); | |
} else { | |
alertUserAboutError(); | |
} | |
} | |
catch (IOException e) { | |
Log.e(TAG, "Exception caught: ", e); | |
} | |
catch (JSONException e) { | |
Log.e(TAG, "Exception caught: ", e); | |
} | |
} | |
}); | |
} | |
else { | |
Toast.makeText(this, getString(R.string.network_unavailable_message), | |
Toast.LENGTH_LONG).show(); | |
} | |
} | |
private void toggleRefresh() { | |
if (mProgressBar.getVisibility() == View.INVISIBLE) { | |
mProgressBar.setVisibility(View.VISIBLE); | |
mRefreshImageView.setVisibility(View.INVISIBLE); | |
} | |
else { | |
mProgressBar.setVisibility(View.INVISIBLE); | |
mRefreshImageView.setVisibility(View.VISIBLE); | |
} | |
} | |
private void updateDisplay() { | |
Current current = mForecast.getCurrent(); | |
mTemperatureLabel.setText(current.getTemperature() + ""); | |
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be"); | |
mHumidityValue.setText(current.getHumidity() + ""); | |
mPrecipValue.setText(current.getPrecipChance() + "%"); | |
mSummaryLabel.setText(current.getSummary()); | |
Drawable drawable = getResources().getDrawable(current.getIconId()); | |
mIconImageView.setImageDrawable(drawable); | |
} | |
private Forecast parseForecastDetails(String jsonData) throws JSONException { | |
Forecast forecast = new Forecast(); | |
forecast.setCurrent(getCurrentDetails(jsonData)); | |
forecast.setHourlyForecast(getHourlyForecast(jsonData)); | |
forecast.setDailyForecast(getDailyForecast(jsonData)); | |
return forecast; | |
} | |
private Day[] getDailyForecast(String jsonData) throws JSONException { | |
JSONObject forecast = new JSONObject(jsonData); | |
String timezone = forecast.getString("timezone"); | |
JSONObject daily = forecast.getJSONObject("daily"); | |
JSONArray data = daily.getJSONArray("data"); | |
Day[] days = new Day[data.length()]; | |
for (int i = 0; i < data.length(); i++) { | |
JSONObject jsonDay = data.getJSONObject(i); | |
Day day = new Day(); | |
day.setSummary(jsonDay.getString("summary")); | |
day.setIcon(jsonDay.getString("icon")); | |
day.setTemperatureMax(jsonDay.getDouble("temperatureMax")); | |
day.setTime(jsonDay.getLong("time")); | |
day.setTimezone(timezone); | |
days[i] = day; | |
} | |
return days; | |
} | |
private Hour[] getHourlyForecast(String jsonData) throws JSONException { | |
JSONObject forecast = new JSONObject(jsonData); | |
String timezone = forecast.getString("timezone"); | |
JSONObject hourly = forecast.getJSONObject("hourly"); | |
JSONArray data = hourly.getJSONArray("data"); | |
Hour[] hours = new Hour[data.length()]; | |
for (int i = 0; i < data.length(); i++) { | |
JSONObject jsonHour = data.getJSONObject(i); | |
Hour hour = new Hour(); | |
hour.setSummary(jsonHour.getString("summary")); | |
hour.setTemperature(jsonHour.getDouble("temperature")); | |
hour.setIcon(jsonHour.getString("icon")); | |
hour.setTime(jsonHour.getLong("time")); | |
hour.setTimezone(timezone); | |
hours[i] = hour; | |
} | |
return hours; | |
} | |
private Current getCurrentDetails(String jsonData) throws JSONException { | |
JSONObject forecast = new JSONObject(jsonData); | |
String timezone = forecast.getString("timezone"); | |
Log.i(TAG, "From JSON: " + timezone); | |
JSONObject currently = forecast.getJSONObject("currently"); | |
Current current = new Current(); | |
current.setHumidity(currently.getDouble("humidity")); | |
current.setTime(currently.getLong("time")); | |
current.setIcon(currently.getString("icon")); | |
current.setPrecipChance(currently.getDouble("precipProbability")); | |
current.setSummary(currently.getString("summary")); | |
current.setTemperature(currently.getDouble("temperature")); | |
current.setTimeZone(timezone); | |
Log.d(TAG, current.getFormattedTime()); | |
return current; | |
} | |
private boolean isNetworkAvailable() { | |
ConnectivityManager manager = (ConnectivityManager) | |
getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = manager.getActiveNetworkInfo(); | |
boolean isAvailable = false; | |
if (networkInfo != null && networkInfo.isConnected()) { | |
isAvailable = true; | |
} | |
return isAvailable; | |
} | |
private void alertUserAboutError() { | |
AlertDialogFragment dialog = new AlertDialogFragment(); | |
dialog.show(getFragmentManager(), "error_dialog"); | |
} | |
@OnClick (R.id.dailyButton) | |
public void startDailyActivity(View view) { | |
Intent intent = new Intent(this, DailyForecastActivity.class); | |
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast()); | |
startActivity(intent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment