Advertisement
yo2man

set the Weather Icon

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