Advertisement
yo2man

Setting the weather, plugging in the data

Jul 9th, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.86 KB | None | 0 0
  1. //Setting the weather, plugging in the data
  2.  
  3. // Right now we're getting weather data,
  4. // when the activity is created, which is when the app starts up.
  5. // That's great, but we can't expect our users to close out the app completely, and
  6. // start it up every time they want to get the latest weather.
  7. // We need to give them a way to update the weather.
  8. // Currently, we are just logging the response from forecast down here in
  9. // the on response call back.
  10. // Let's add a new method, to update the display.
  11.  
  12.  
  13. //----------------------------------------------------------------------------------
  14. MainActivity.java
  15.  
  16. package com.teamtreehouse.stormy;
  17.  
  18. import android.content.Context;
  19. import android.net.ConnectivityManager;
  20. import android.net.NetworkInfo;
  21. import android.support.v7.app.ActionBarActivity;
  22. import android.os.Bundle;
  23. import android.util.Log;
  24. import android.widget.ImageView;
  25. import android.widget.TextView;
  26. import android.widget.Toast;
  27.  
  28. import com.squareup.okhttp.Call;
  29. import com.squareup.okhttp.Callback;
  30. import com.squareup.okhttp.OkHttpClient;
  31. import com.squareup.okhttp.Request;
  32. import com.squareup.okhttp.Response;
  33.  
  34. import org.json.JSONException;
  35. import org.json.JSONObject;
  36.  
  37. import java.io.IOException;
  38.  
  39. import butterknife.ButterKnife;
  40. import butterknife.InjectView;
  41.  
  42.  
  43. public class MainActivity extends ActionBarActivity {
  44.  
  45.     public static final String TAG = MainActivity.class.getSimpleName();
  46.  
  47.     private CurrentWeather mCurrentWeather;
  48.  
  49.     @InjectView(R.id.timeLabel) TextView mTimeLabel; //doing it with butterknife annotation
  50.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  51.     @InjectView(R.id.humidityLabel) TextView mHumidityValue;
  52.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  53.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  54.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  55.     //create new method to check for network connectivity
  56.  
  57.     @Override
  58.     protected void onCreate(Bundle savedInstanceState) {
  59.         super.onCreate(savedInstanceState);
  60.         setContentView(R.layout.activity_main);
  61.         ButterKnife.inject(this); //butterknife
  62.  
  63.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  64.         double latitude = 37.8267;
  65.         double longitude = -122.423;
  66.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  67.                 "/" + latitude + "," + longitude;
  68.  
  69.         if (isNetworkAvailable()) {
  70.             OkHttpClient client = new OkHttpClient();
  71.             Request request = new Request.Builder().url(forecastUrl).build();
  72.  
  73.             Call call = client.newCall(request);
  74.             call.enqueue(new Callback() {
  75.                 @Override
  76.                 public void onFailure(Request request, IOException e) {
  77.  
  78.                 }
  79.  
  80.                 @Override
  81.                 public void onResponse(Response response) throws IOException {
  82.                     try {
  83.                         String jsonData = response.body().string();
  84.                         Log.v(TAG,jsonData );
  85.                         if (response.isSuccessful()) {
  86.                             mCurrentWeather = getCurrentDetails(jsonData);
  87.  
  88.                             //can't do it in background thread because only the main thread is allowed to update the UI like we stated before
  89.                             // What we need to do is send a message to the main UI thread that we have code ready for it.
  90.                             // We can do this a few different ways, but
  91.                             // we'll use a simple one using a special helper method called runOnUIThread.
  92.                             runOnUiThread(new Runnable() {
  93.                                 @Override
  94.                                 public void run() {
  95.                                     updateDisplay(); //create  a new method for update display instead of putting it here so code isn't messy
  96.                                 }
  97.                             });
  98.                         } else {
  99.                             alertUserAboutError();
  100.                         }
  101.                     }
  102.                     catch (IOException e) {
  103.                         Log.e(TAG, "Exception caught: ", e);
  104.                     }
  105.                     catch (JSONException e){
  106.                         Log.e(TAG, "Exception caught: ", e);
  107.                     }
  108.                 }
  109.             });
  110.         }
  111.             else {
  112.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  113.         }
  114.  
  115.         Log.d(TAG, "Main UI code is running!");
  116.     }
  117.  
  118.     private void updateDisplay() {
  119.         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.
  120.         mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
  121.         mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
  122.         mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
  123.         mSummaryLabel.setText(mCurrentWeather.getSummary());
  124.         //pretty simple stuff^
  125.     }
  126.  
  127.     private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
  128.  
  129.         JSONObject forecast = new JSONObject(jsonData);
  130.  
  131.         String timezone = forecast.getString("timezone");
  132.             Log.i(TAG, "From JSON: " + timezone);
  133.  
  134.         JSONObject currently = forecast.getJSONObject("currently");
  135.         CurrentWeather currentWeather = new CurrentWeather();
  136.         currentWeather.setHumidity(currently.getDouble("humidity"));
  137.         currentWeather.setTime(currently.getLong("time"));
  138.         currentWeather.setIcon(currently.getString("icon"));
  139.         currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
  140.         currentWeather.setSummary(currently.getString("summary"));
  141.         currentWeather.setTemperature(currently.getDouble("temperature"));
  142.         currentWeather.setTimeZone(timezone);
  143.  
  144.         Log.d(TAG, currentWeather.getFormattedTime());
  145.  
  146.         return currentWeather;
  147.  
  148.     }
  149.  
  150.     private boolean isNetworkAvailable() {
  151.         ConnectivityManager manager = (ConnectivityManager)
  152.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  153.  
  154.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  155.         boolean isAvailable = false;
  156.         if (networkInfo != null && networkInfo.isConnected()) {
  157.             isAvailable = true;
  158.         }
  159.         return isAvailable;
  160.     }
  161.     private void alertUserAboutError() {
  162.         AlertDialogFragment dialog = new AlertDialogFragment();
  163.         dialog.show(getFragmentManager(), "error_dialog");
  164.     }
  165. }
  166.  
  167. //---------------------------------------------------------------------------
  168.  
  169. CurrentWeather.java
  170.  
  171. package com.teamtreehouse.stormy;
  172.  
  173. import java.text.SimpleDateFormat;
  174. import java.util.Date;
  175. import java.util.TimeZone;
  176.  
  177. public class CurrentWeather {
  178.  
  179.     private String mIcon; // The Icon // it comes from Forecast API as a string, we convert it to an int
  180.     private long mTime; //Time
  181.     private double mTemperature; //Temp
  182.     private double mHumidity; //humidity
  183.     private double mPrecipChance; //chance of precipitation
  184.     private String mSummary; //summary at the bottom
  185.  
  186.     private String mTimeZone;
  187.  
  188.     public String getTimeZone() {
  189.         return mTimeZone;
  190.     }
  191.  
  192.     public void setTimeZone(String timeZone) {
  193.         mTimeZone = timeZone;
  194.     }
  195.  
  196.     // Step 2: Generate getters and setters for everything: Code>Generate...>Getters and Setters:
  197.     public double getHumidity() {
  198.         return mHumidity;
  199.     }
  200.  
  201.     public void setHumidity(double humidity) {
  202.         mHumidity = humidity;
  203.     }
  204.  
  205.     public String getIcon() {
  206.         return mIcon;
  207.     }
  208.     // now we want to add a new method to our model that gets the appropriate image
  209.     // based on the icon value we are getting from the forecast API.
  210.     // To get the image, we need to int ID that gets generated for each drawable resource.
  211.  
  212.     public int getIconId(){
  213.         // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
  214.         int iconId = R.drawable.clear_day; //set this one in default, forecast api documentation says to "set a sensible icon as default"
  215.  
  216.         if(mIcon.equals("clear-day")){
  217.             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
  218.         }
  219.         else if (mIcon.equals("clear-night")){
  220.             iconId = R.drawable.clear_night;
  221.         }
  222.         else if (mIcon.equals("rain")) {
  223.             iconId = R.drawable.rain;
  224.         }
  225.         else if (mIcon.equals("snow")) {
  226.             iconId = R.drawable.snow;
  227.         }
  228.         else if (mIcon.equals("sleet")) {
  229.             iconId = R.drawable.sleet;
  230.         }
  231.         else if (mIcon.equals("wind")) {
  232.             iconId = R.drawable.wind;
  233.         }
  234.         else if (mIcon.equals("fog")) {
  235.             iconId = R.drawable.fog;
  236.         }
  237.         else if (mIcon.equals("cloudy")) {
  238.             iconId = R.drawable.cloudy;
  239.         }
  240.         else if (mIcon.equals("partly-cloudy-day")) {
  241.             iconId = R.drawable.partly_cloudy;
  242.         }
  243.         else if (mIcon.equals("partly-cloudy-night")) {
  244.             iconId = R.drawable.cloudy_night;
  245.         }
  246.  
  247.         return iconId;
  248.     }
  249.  
  250.     public void setIcon(String icon) {
  251.         mIcon = icon;
  252.     }
  253.  
  254.     public int getPrecipChance() {
  255.         double precipPercentage = mPrecipChance * 100; //like what we did with mTemperature
  256.         return (int)Math.round(precipPercentage);
  257.     }
  258.  
  259.     public void setPrecipChance(double precipChance) {
  260.         mPrecipChance = precipChance;
  261.     }
  262.  
  263.     public String getSummary() {
  264.         return mSummary;
  265.     }
  266.  
  267.     public void setSummary(String summary) {
  268.         mSummary = summary;
  269.     }
  270.  
  271.     public int getTemperature() {
  272.         return (int)Math.round(mTemperature); //return rounded decimal places of temperature that is cast to an int
  273.     }
  274.  
  275.     public void setTemperature(double temperature) {
  276.         mTemperature = temperature;
  277.     }
  278.  
  279.     public long getTime() {
  280.         return mTime;
  281.     }
  282.  
  283.     public String getFormattedTime() {
  284.         SimpleDateFormat formatter = new SimpleDateFormat("h:mm, a"); // this special Java called SimpleDateFormat converts unix date format to locale "normal" format
  285.         formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); //set time zone, logging it from MainActivity
  286.  
  287.         Date dateTime = new Date(getTime() * 1000);
  288.         String timeString = formatter.format(dateTime);
  289.  
  290.         return timeString;
  291.     }
  292.  
  293.     public void setTime(long time) {
  294.         mTime = time;
  295.     }
  296.  
  297. }
  298.  
  299.  
  300. // https://teamtreehouse.com/library/build-a-weather-app/hooking-up-the-model-to-the-view/plugging-in-the-data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement