Advertisement
yo2man

Formatting date / Importing and using image icons

Jul 8th, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.92 KB | None | 0 0
  1. // Formatting date / Importing and using image icons
  2. // now we want to add a new method to our model that gets the appropriate image
  3. // based on the icon value we are getting from the forecast API.
  4. // To get the image, we need to int ID that gets generated for each drawable resource.
  5.  
  6. To import the image icons, download and extract them. Then copy the four drawable folders.
  7.  
  8. Right click on res folder in android studio>show in explorer> click on res folder again> paste in the drawable folders
  9.  
  10.  
  11. //------------------------------------------------------------------------------------
  12.  
  13. MainActivity.java
  14.  
  15. package com.teamtreehouse.stormy;
  16.  
  17. import android.content.Context;
  18. import android.net.ConnectivityManager;
  19. import android.net.NetworkInfo;
  20. import android.support.v7.app.ActionBarActivity;
  21. import android.os.Bundle;
  22. import android.util.Log;
  23. import android.widget.Toast;
  24.  
  25. import com.squareup.okhttp.Call;
  26. import com.squareup.okhttp.Callback;
  27. import com.squareup.okhttp.OkHttpClient;
  28. import com.squareup.okhttp.Request;
  29. import com.squareup.okhttp.Response;
  30.  
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33.  
  34. import java.io.IOException;
  35.  
  36.  
  37. public class MainActivity extends ActionBarActivity {
  38.  
  39.     public static final String TAG = MainActivity.class.getSimpleName();
  40.  
  41.     private CurrentWeather mCurrentWeather; // CurrentWeather.java
  42.  
  43.     //create new method to check for network connectivity
  44.  
  45.     @Override
  46.     protected void onCreate(Bundle savedInstanceState) {
  47.         super.onCreate(savedInstanceState);
  48.         setContentView(R.layout.activity_main);
  49.  
  50.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  51.         double latitude = 37.8267;
  52.         double longitude = -122.423;
  53.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  54.                 "/" + latitude + "," + longitude;
  55.  
  56.         if (isNetworkAvailable()) {
  57.             OkHttpClient client = new OkHttpClient();
  58.             Request request = new Request.Builder().url(forecastUrl).build();
  59.  
  60.             Call call = client.newCall(request);
  61.             call.enqueue(new Callback() {
  62.                 @Override
  63.                 public void onFailure(Request request, IOException e) {
  64.  
  65.                 }
  66.  
  67.                 @Override
  68.                 public void onResponse(Response response) throws IOException {
  69.                     try {
  70.                         String jsonData = response.body().string(); //pass in Json Data as string*
  71.                         Log.v(TAG,jsonData ); // pass in (jsonData)*
  72.                         if (response.isSuccessful()) {
  73.                             mCurrentWeather = getCurrentDetails(jsonData); //if response is successful, set current weather  //(jsonData)* //[2]
  74.                         } else {
  75.                             alertUserAboutError();
  76.                         }
  77.                     }
  78.                     catch (IOException e) {
  79.                         Log.e(TAG, "Exception caught: ", e);
  80.                     }
  81.                     catch (JSONException e){ //[2]
  82.                         Log.e(TAG, "Exception caught: ", e);
  83.                     }
  84.                 }
  85.             });
  86.         }
  87.             else {
  88.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  89.         }
  90.  
  91.         Log.d(TAG, "Main UI code is running!");
  92.     }
  93.  
  94.     private CurrentWeather getCurrentDetails(String jsonData) throws JSONException { //this throws technique for handling exception is basically moving the responsibility of handling the exception to whomever calls this method[2]
  95.  
  96.         // We're gonna work with a special class called jsonObject. //JSONObject is a public method
  97.         // This class can hold any object represented in the json format, and its properties can be accessed using a few different methods.
  98.         JSONObject forecast = new JSONObject(jsonData); // The json object class has a constructor lets us pass in a string of jsonData to create a new JSON object
  99.  
  100.         // Access timezone info from JSON API https://api.forecast.io/forecast/d5faf0cb201f103df4dde0b8b0a4f490/37.8267,-122.423
  101.         String timezone = forecast.getString("timezone"); // pass in key from JSON: "timezone"
  102.             Log.i(TAG, "From JSON: " + timezone); // ^ log this
  103.  
  104.         JSONObject currently = forecast.getJSONObject("currently"); //get JSONObject "currently" from forecast.api
  105.         //^ And now from this JSONObject, we have all the data we need to create our current weather object :
  106.         CurrentWeather currentWeather = new CurrentWeather();
  107.         currentWeather.setHumidity(currently.getDouble("humidity"));
  108.         currentWeather.setTime(currently.getLong("time"));
  109.         currentWeather.setIcon(currently.getString("icon"));
  110.         currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
  111.         currentWeather.setSummary(currently.getString("summary"));
  112.         currentWeather.setTemperature(currently.getDouble("temperature"));
  113.         currentWeather.setTimeZone(timezone);
  114.  
  115.         Log.d(TAG, currentWeather.getFormattedTime());
  116.  
  117.         return currentWeather;
  118.  
  119.     }
  120.  
  121.     private boolean isNetworkAvailable() {
  122.         ConnectivityManager manager = (ConnectivityManager)
  123.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  124.  
  125.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  126.         boolean isAvailable = false;
  127.         if (networkInfo != null && networkInfo.isConnected()) {
  128.             isAvailable = true; //[**]
  129.         }
  130.         return isAvailable;
  131.     }
  132.     private void alertUserAboutError() {
  133.         AlertDialogFragment dialog = new AlertDialogFragment();
  134.         dialog.show(getFragmentManager(), "error_dialog");
  135.     }
  136. }
  137.  
  138. //------------------------------------------------------------------------------------
  139.  
  140. CurrentWeather.java
  141.  
  142. package com.teamtreehouse.stormy;
  143.  
  144. import java.text.SimpleDateFormat;
  145. import java.util.Date;
  146. import java.util.TimeZone;
  147.  
  148. public class CurrentWeather {
  149.  
  150.     private String mIcon; // The Icon // it comes from Forecast API as a string, we convert it to an int
  151.     private long mTime; //Time
  152.     private double mTemperature; //Temp
  153.     private double mHumidity; //humidity
  154.     private double mPrecipChance; //chance of precipitation
  155.     private String mSummary; //summary at the bottom
  156.  
  157.     private String mTimeZone;
  158.  
  159.     public String getTimeZone() {
  160.         return mTimeZone;
  161.     }
  162.  
  163.     public void setTimeZone(String timeZone) {
  164.         mTimeZone = timeZone;
  165.     }
  166.  
  167.     // Step 2: Generate getters and setters for everything: Code>Generate...>Getters and Setters:
  168.     public double getHumidity() {
  169.         return mHumidity;
  170.     }
  171.  
  172.     public void setHumidity(double humidity) {
  173.         mHumidity = humidity;
  174.     }
  175.  
  176.     public String getIcon() {
  177.         return mIcon;
  178.     }
  179.     // now we want to add a new method to our model that gets the appropriate image
  180.     // based on the icon value we are getting from the forecast API.
  181.     // To get the image, we need to int ID that gets generated for each drawable resource.
  182.  
  183.     public int getIconId(){
  184.         // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
  185.         int iconId = R.drawable.clear_day; //set this one in default, forecast api documentation says to "set a sensible icon as default"
  186.  
  187.         if(mIcon.equals("clear-day")){
  188.             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
  189.         }
  190.         else if (mIcon.equals("clear-night")){
  191.             iconId = R.drawable.clear_night;
  192.         }
  193.         else if (mIcon.equals("rain")) {
  194.             iconId = R.drawable.rain;
  195.         }
  196.         else if (mIcon.equals("snow")) {
  197.             iconId = R.drawable.snow;
  198.         }
  199.         else if (mIcon.equals("sleet")) {
  200.             iconId = R.drawable.sleet;
  201.         }
  202.         else if (mIcon.equals("wind")) {
  203.             iconId = R.drawable.wind;
  204.         }
  205.         else if (mIcon.equals("fog")) {
  206.             iconId = R.drawable.fog;
  207.         }
  208.         else if (mIcon.equals("cloudy")) {
  209.             iconId = R.drawable.cloudy;
  210.         }
  211.         else if (mIcon.equals("partly-cloudy-day")) {
  212.             iconId = R.drawable.partly_cloudy;
  213.         }
  214.         else if (mIcon.equals("partly-cloudy-night")) {
  215.             iconId = R.drawable.cloudy_night;
  216.         }
  217.  
  218.         return iconId;
  219.     }
  220.  
  221.     public void setIcon(String icon) {
  222.         mIcon = icon;
  223.     }
  224.  
  225.     public double getPrecipChance() {
  226.         return mPrecipChance;
  227.     }
  228.  
  229.     public void setPrecipChance(double precipChance) {
  230.         mPrecipChance = precipChance;
  231.     }
  232.  
  233.     public String getSummary() {
  234.         return mSummary;
  235.     }
  236.  
  237.     public void setSummary(String summary) {
  238.         mSummary = summary;
  239.     }
  240.  
  241.     public double getTemperature() {
  242.         return mTemperature;
  243.     }
  244.  
  245.     public void setTemperature(double temperature) {
  246.         mTemperature = temperature;
  247.     }
  248.  
  249.     public long getTime() {
  250.         return mTime;
  251.     }
  252.  
  253.     public String getFormattedTime() {
  254.         SimpleDateFormat formatter = new SimpleDateFormat("h:mm, a"); // this special Java called SimpleDateFormat converts unix date format to locale "normal" format
  255.         formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); //set time zone, logging it from MainActivity
  256.  
  257.         Date dateTime = new Date(getTime() * 1000);
  258.         String timeString = formatter.format(dateTime);
  259.  
  260.         return timeString;
  261.     }
  262.  
  263.     public void setTime(long time) {
  264.         mTime = time;
  265.     }
  266.  
  267. }
  268.  
  269. //
  270. // https://teamtreehouse.com/library/build-a-weather-app/working-with-json/setting-currentweather-from-json
  271. // https://teamtreehouse.com/library/build-a-weather-app/working-with-json/cleaning-up-the-date-and-time
  272. // http://teamtreehouse.com/library/build-a-weather-app/working-with-json/setting-the-weather-icon
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement