Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // set the Weather Icon
- //--------------------------------------------------------------------
- MainActivity.java
- package com.teamtreehouse.stormy;
- import android.content.Context;
- import android.graphics.drawable.Drawable;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.ImageView;
- 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.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- import butterknife.ButterKnife;
- import butterknife.InjectView;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG = MainActivity.class.getSimpleName();
- private CurrentWeather mCurrentWeather;
- @InjectView(R.id.timeLabel) TextView mTimeLabel; //doing it with butterknife annotation
- @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;
- //create new method to check for network connectivity
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.inject(this); //butterknife
- String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
- double latitude = 37.8267;
- double longitude = -122.423;
- String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
- "/" + latitude + "," + longitude;
- if (isNetworkAvailable()) {
- 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) {
- }
- @Override
- public void onResponse(Response response) throws IOException {
- try {
- String jsonData = response.body().string();
- Log.v(TAG,jsonData );
- if (response.isSuccessful()) {
- mCurrentWeather = getCurrentDetails(jsonData);
- //can't do it in background thread because only the main thread is allowed to update the UI like we stated before
- // What we need to do is send a message to the main UI thread that we have code ready for it.
- // We can do this a few different ways, but
- // we'll use a simple one using a special helper method called runOnUIThread.
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- updateDisplay(); //create a new method for update display instead of putting it here so code isn't messy
- }
- });
- } 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();
- }
- Log.d(TAG, "Main UI code is running!");
- }
- private void updateDisplay() {
- mTemperatureLabel.setText(mCurrentWeather.getTemperature() + ""); // the temperature u get from .getTemperature is a 'Double' value thus you have to convert it to a string via + "" . simple.
- mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
- mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
- mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
- mSummaryLabel.setText(mCurrentWeather.getSummary());
- Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
- mIconImageView.setImageDrawable(drawable);
- //pretty simple stuff^
- }
- private CurrentWeather 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");
- CurrentWeather currentWeather = new CurrentWeather();
- currentWeather.setHumidity(currently.getDouble("humidity"));
- currentWeather.setTime(currently.getLong("time"));
- currentWeather.setIcon(currently.getString("icon"));
- currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
- currentWeather.setSummary(currently.getString("summary"));
- currentWeather.setTemperature(currently.getDouble("temperature"));
- currentWeather.setTimeZone(timezone);
- Log.d(TAG, currentWeather.getFormattedTime());
- return currentWeather;
- }
- 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");
- }
- }
- //----------------------------------------------------------------------------------
- CurrentWeather.java
- package com.teamtreehouse.stormy;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.TimeZone;
- public class CurrentWeather {
- private String mIcon; // The Icon // it comes from Forecast API as a string, we convert it to an int
- private long mTime; //Time
- private double mTemperature; //Temp
- private double mHumidity; //humidity
- private double mPrecipChance; //chance of precipitation
- private String mSummary; //summary at the bottom
- private String mTimeZone;
- public String getTimeZone() {
- return mTimeZone;
- }
- public void setTimeZone(String timeZone) {
- mTimeZone = timeZone;
- }
- // Step 2: Generate getters and setters for everything: Code>Generate...>Getters and Setters:
- public double getHumidity() {
- return mHumidity;
- }
- public void setHumidity(double humidity) {
- mHumidity = humidity;
- }
- public String getIcon() {
- return mIcon;
- }
- // now we want to add a new method to our model that gets the appropriate image
- // based on the icon value we are getting from the forecast API.
- // To get the image, we need to int ID that gets generated for each drawable resource.
- public int getIconId(){
- // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
- int iconId = R.drawable.clear_day; //set this one in default, forecast api documentation says to "set a sensible icon as default"
- if(mIcon.equals("clear-day")){
- iconId = R.drawable.clear_day; //notice that the ids have _ compared to string "-" because we arent allowed to have dashes as resource names in Android Studio
- }
- else if (mIcon.equals("clear-night")){
- iconId = R.drawable.clear_night;
- }
- else if (mIcon.equals("rain")) {
- iconId = R.drawable.rain;
- }
- else if (mIcon.equals("snow")) {
- iconId = R.drawable.snow;
- }
- else if (mIcon.equals("sleet")) {
- iconId = R.drawable.sleet;
- }
- else if (mIcon.equals("wind")) {
- iconId = R.drawable.wind;
- }
- else if (mIcon.equals("fog")) {
- iconId = R.drawable.fog;
- }
- else if (mIcon.equals("cloudy")) {
- iconId = R.drawable.cloudy;
- }
- else if (mIcon.equals("partly-cloudy-day")) {
- iconId = R.drawable.partly_cloudy;
- }
- else if (mIcon.equals("partly-cloudy-night")) {
- iconId = R.drawable.cloudy_night;
- }
- return iconId;
- }
- public void setIcon(String icon) {
- mIcon = icon;
- }
- public int getPrecipChance() {
- double precipPercentage = mPrecipChance * 100; //like what we did with mTemperature
- return (int)Math.round(precipPercentage);
- }
- public void setPrecipChance(double precipChance) {
- mPrecipChance = precipChance;
- }
- public String getSummary() {
- return mSummary;
- }
- public void setSummary(String summary) {
- mSummary = summary;
- }
- public int getTemperature() {
- return (int)Math.round(mTemperature); //return rounded decimal places of temperature that is cast to an int
- }
- public void setTemperature(double temperature) {
- mTemperature = temperature;
- }
- public long getTime() {
- return mTime;
- }
- public String getFormattedTime() {
- SimpleDateFormat formatter = new SimpleDateFormat("h:mm, a"); // this special Java called SimpleDateFormat converts unix date format to locale "normal" format
- formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); //set time zone, logging it from MainActivity
- Date dateTime = new Date(getTime() * 1000);
- String timeString = formatter.format(dateTime);
- return timeString;
- }
- public void setTime(long time) {
- mTime = time;
- }
- }
- // https://teamtreehouse.com/forum/hooking-up-data-to-textview-weather-app <-this guy explains the concepts pretty well in the challenges
- // https://teamtreehouse.com/library/build-a-weather-app/hooking-up-the-model-to-the-view/setting-the-weather-icon
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement