Advertisement
yo2man

JSONArrays

Jul 11th, 2015
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.95 KB | None | 0 0
  1. //JSON Arrays
  2.  
  3. // So far we've utilized the JSON object class to work with our JSON data.
  4. // Now we're going to look at the other important class for
  5. // JSON in Android, JSON array.
  6.  
  7. /*
  8. Remember that JSON object is stored in two different ways:
  9.     1. A collection of key/value pairs grouped together into an object
  10.     2. An ordered list of object <--- this is the JSONArray
  11. */
  12.  
  13. JSONObject and JSONArray image:
  14. http://content.screencast.com/users/yofu1234/folders/Jing/media/46242fcf-4b03-45e3-9e41-fee0d15483af/JSONArray%20and%20JSONObject.png
  15.  
  16.  
  17. Forecast Api JSON:
  18. data: [  <---this is the JSONarray   data[]
  19.  
  20. {     <--- these are the JSONObjects{}
  21.  
  22.     "time": 1436665740,
  23.     "precipIntensity": 0,
  24.     "precipProbability": 0
  25.  
  26. },
  27. {
  28.  
  29.     "time": 1436665800,
  30.     "precipIntensity": 0,
  31.     "precipProbability": 0
  32.  
  33. },
  34. {
  35.  
  36.     "time": 1436665860,
  37.     "precipIntensity": 0,
  38.     "precipProbability": 0
  39.  
  40. },
  41.  
  42. // We will access this data array in code, and
  43. // then store each object in here as an array item using our new hour class.
  44.  
  45. // Let's go back to our new method, parseForecastDetails.
  46. // Our forecast class has two arrays to fill so let's create two new methods to fill
  47. // them, following the format we used to fill the current weather data.
  48.  
  49.  
  50. package com.teamtreehouse.stormy.UI;
  51.  
  52. import android.content.Context;
  53. import android.graphics.drawable.Drawable;
  54. import android.net.ConnectivityManager;
  55. import android.net.NetworkInfo;
  56. import android.support.v7.app.ActionBarActivity;
  57. import android.os.Bundle;
  58. import android.util.Log;
  59. import android.view.View;
  60. import android.widget.ImageView;
  61. import android.widget.ProgressBar;
  62. import android.widget.TextView;
  63. import android.widget.Toast;
  64.  
  65. import com.squareup.okhttp.Call;
  66. import com.squareup.okhttp.Callback;
  67. import com.squareup.okhttp.OkHttpClient;
  68. import com.squareup.okhttp.Request;
  69. import com.squareup.okhttp.Response;
  70. import com.teamtreehouse.stormy.R;
  71. import com.teamtreehouse.stormy.weather.Current;
  72. import com.teamtreehouse.stormy.weather.Day;
  73. import com.teamtreehouse.stormy.weather.Forecast;
  74. import com.teamtreehouse.stormy.weather.Hour;
  75.  
  76. import org.json.JSONArray;
  77. import org.json.JSONException;
  78. import org.json.JSONObject;
  79.  
  80. import java.io.IOException;
  81.  
  82. import butterknife.ButterKnife;
  83. import butterknife.InjectView;
  84.  
  85.  
  86. public class MainActivity extends ActionBarActivity {
  87.  
  88.     public static final String TAG = MainActivity.class.getSimpleName();
  89.  
  90.     private Forecast mForecast;
  91.  
  92.     @InjectView(R.id.timeLabel) TextView mTimeLabel;
  93.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  94.     @InjectView(R.id.humidityValue) TextView mHumidityValue;
  95.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  96.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  97.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  98.     @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  99.     @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  100.  
  101.     @Override
  102.     protected void onCreate(Bundle savedInstanceState) {
  103.         super.onCreate(savedInstanceState);
  104.         setContentView(R.layout.activity_main);
  105.         ButterKnife.inject(this);
  106.  
  107.         mProgressBar.setVisibility(View.INVISIBLE);
  108.  
  109.         final double latitude = 37.8267;
  110.         final double longitude = -122.423;
  111.  
  112.         mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  113.             @Override
  114.             public void onClick(View v) {
  115.                 getForecast(latitude, longitude);
  116.  
  117.             }
  118.         });
  119.  
  120.         getForecast(latitude, longitude);
  121.  
  122.         Log.d(TAG, "Main UI code is running!");
  123.     }
  124.  
  125.     private void getForecast(double latitude, double longitude) {
  126.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  127.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  128.                 "/" + latitude + "," + longitude;
  129.  
  130.         if (isNetworkAvailable()) {
  131.             toggleRefresh();
  132.  
  133.             OkHttpClient client = new OkHttpClient();
  134.             Request request = new Request.Builder().url(forecastUrl).build();
  135.  
  136.             Call call = client.newCall(request);
  137.             call.enqueue(new Callback() {
  138.                 @Override
  139.                 public void onFailure(Request request, IOException e) {
  140.                     runOnUiThread(new Runnable(){
  141.                         @Override
  142.                         public void run(){
  143.                             toggleRefresh();
  144.                         }
  145.                     });
  146.                     alertUserAboutError();
  147.                 }
  148.  
  149.                 @Override
  150.                 public void onResponse(Response response) throws IOException {
  151.                     runOnUiThread(new Runnable(){
  152.                         @Override
  153.                         public void run(){
  154.                             toggleRefresh();
  155.                         }
  156.                     });
  157.                     try {
  158.                         String jsonData = response.body().string();
  159.                         Log.v(TAG, jsonData);
  160.                         if (response.isSuccessful()) {
  161.                             mForecast = parseForecastDetails(jsonData);
  162.                             runOnUiThread(new Runnable() {
  163.                                 @Override
  164.                                 public void run() {
  165.                                     updateDisplay();
  166.                                 }
  167.                             });
  168.                         } else {
  169.                             alertUserAboutError();
  170.                         }
  171.                     } catch (IOException e) {
  172.                         Log.e(TAG, "Exception caught: ", e);
  173.                     } catch (JSONException e) {
  174.                         Log.e(TAG, "Exception caught: ", e);
  175.                     }
  176.                 }
  177.             });
  178.         }
  179.             else {
  180.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  181.         }
  182.     }
  183.  
  184.     private void toggleRefresh() {
  185.         if(mProgressBar.getVisibility() == View.INVISIBLE) {
  186.             mProgressBar.setVisibility(View.VISIBLE);
  187.             mRefreshImageView.setVisibility(View.INVISIBLE);
  188.         }
  189.         else {
  190.             mProgressBar.setVisibility(View.INVISIBLE);
  191.             mRefreshImageView.setVisibility(View.VISIBLE);
  192.         }
  193.     }
  194.  
  195.     private void updateDisplay() {
  196.         Current current = mForecast.getCurrent();
  197.  
  198.         mTemperatureLabel.setText(current.getTemperature() + "");
  199.         mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
  200.         mHumidityValue.setText(current.getHumidity() + "");
  201.         mPrecipValue.setText(current.getPrecipChance() + "%");
  202.         mSummaryLabel.setText(current.getSummary());
  203.  
  204.         Drawable drawable = getResources().getDrawable(current.getIconId());
  205.         mIconImageView.setImageDrawable(drawable);
  206.     }
  207.  
  208.     private Forecast parseForecastDetails(String jsonData) throws JSONException  {
  209.         Forecast forecast = new Forecast();
  210.  
  211.         // Our forecast class has two Arrays to fill so let's create two new methods to fill
  212.         // then, following the format we used to fill the current weather data.
  213.         // We write the code we want, and then generate the new method declarations.
  214.         forecast.setCurrent(getCurrentDetails(jsonData));
  215.         forecast.setHourlyForecast(getHourlyForecast(jsonData)); //So here we want the code to be forecast.setHourlyForecast, and we wanna call a new method which we will call getHourlyForecast and we're gonna pass in the JSON data. *
  216.         forecast.setDailyForecast(getDailyForecast(jsonData));  //Then we'll do the same thing, forecast.setDailyForecast, and again, we'll have a new method, getDailyForecast with jsonData. Then use alt+enter to generate the getHourlyForecast and the getDailyForecast *
  217.         return forecast;
  218.     }
  219.  
  220.     private Day[] getDailyForecast(String jsonData) { //*
  221.         return new Day[0];
  222.     }
  223.  
  224.     private Hour[] getHourlyForecast(String jsonData) throws JSONException{ //*
  225.         JSONObject forecast = new JSONObject(jsonData); //we want a JSONObject
  226.         String timezone = forecast.getString("timezone"); //we also want to get the timezone
  227.  
  228.         JSONObject hourly = forecast.getJSONObject("hourly"); //[*3*] we'll name it hourly to match. Then we'll pass in the "hourly" key
  229.         // ^So what this line does, is it takes the forecast JSONObject at the root. And it gets the JSONObject at that root level, named hourly. thus forecast.getJSONObject{"hourly"}
  230.  
  231.         // Now that we have that object, we can access the array which is a property of that object
  232.         JSONArray data = hourly.getJSONArray("data"); //pass in the key "data"
  233.         // Okay, so we have an array of JSON objects, hooray.
  234.         //But we want an array of our objects.
  235.         // How should we go about converting them?
  236.  
  237.  
  238.        /* JSON data from Forecast.api
  239.        { <-- JSON object corresponds to the JSON object that starts with this curly brace. So we can access each of these properties just like we accessed the time zone property.
  240.             "latitude": 37.8267,
  241.              "longitude": -122.423,
  242.              "timezone": "America/Los_Angeles",
  243.              "offset": -7,
  244.              currently: {...}
  245.              minutely: {...}
  246.              hourly: {                                         <------ we want to get this JSONObject that is accessed by the key "hourly" so back in our code we are going to create a new JSON Object...[*3*]
  247.                 "summary": "Mostly cloudy throughout the day.",
  248.                 "icon": "partly-cloudy-night",
  249.                 "data":
  250.                         [
  251.                         {...}
  252.                         {...}
  253.                         {
  254.                         "time": 1436662800,
  255.                         "summary": "Partly Cloudy",
  256.                         "icon": "partly-cloudy-day",
  257.                         "precipIntensity": 0,
  258.                         "precipProbability": 0,
  259.                         "temperature": 65.39,
  260.                         "apparentTemperature": 65.39,
  261.                         "dewPoint": 53.82,
  262.                         "humidity": 0.66,
  263.                         "windSpeed": 13.04,
  264.                         "windBearing": 268,
  265.                         "visibility": 9.65,
  266.                         "cloudCover": 0.36,
  267.                         "pressure": 1014.91,
  268.                         "ozone": 327.73
  269.              }
  270.  
  271.  
  272.         */
  273.     }
  274.  
  275.     private Current getCurrentDetails(String jsonData) throws JSONException {
  276.  
  277.         JSONObject forecast = new JSONObject(jsonData);
  278.         String timezone = forecast.getString("timezone");
  279.             Log.i(TAG, "From JSON: " + timezone);
  280.  
  281.         JSONObject currently = forecast.getJSONObject("currently");
  282.  
  283.         Current current = new Current();
  284.         current.setHumidity(currently.getDouble("humidity"));
  285.         current.setTime(currently.getLong("time"));
  286.         current.setIcon(currently.getString("icon"));
  287.         current.setPrecipChance(currently.getDouble("precipProbability"));
  288.         current.setSummary(currently.getString("summary"));
  289.         current.setTemperature(currently.getDouble("temperature"));
  290.         current.setTimeZone(timezone);
  291.  
  292.         Log.d(TAG, current.getFormattedTime());
  293.  
  294.         return current;
  295.  
  296.     }
  297.  
  298.     private boolean isNetworkAvailable() {
  299.         ConnectivityManager manager = (ConnectivityManager)
  300.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  301.  
  302.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  303.         boolean isAvailable = false;
  304.         if (networkInfo != null && networkInfo.isConnected()) {
  305.             isAvailable = true;
  306.         }
  307.         return isAvailable;
  308.     }
  309.     private void alertUserAboutError() {
  310.         AlertDialogFragment dialog = new AlertDialogFragment();
  311.         dialog.show(getFragmentManager(), "error_dialog");
  312.     }
  313. }
  314.  
  315.  
  316.  
  317.  
  318. // android documentation: http://developer.android.com/reference/org/json/JSONArray.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement