Advertisement
yo2man

JSON array to a Java array | last lesson

Jul 12th, 2015
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.69 KB | None | 0 0
  1. // JSON array to a Java array last lesson
  2.  
  3. MainActivity.java
  4.  
  5. package com.teamtreehouse.stormy.UI;
  6.  
  7. import android.content.Context;
  8. import android.graphics.drawable.Drawable;
  9. import android.net.ConnectivityManager;
  10. import android.net.NetworkInfo;
  11. import android.support.v7.app.ActionBarActivity;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.ImageView;
  16. import android.widget.ProgressBar;
  17. import android.widget.TextView;
  18. import android.widget.Toast;
  19.  
  20. import com.squareup.okhttp.Call;
  21. import com.squareup.okhttp.Callback;
  22. import com.squareup.okhttp.OkHttpClient;
  23. import com.squareup.okhttp.Request;
  24. import com.squareup.okhttp.Response;
  25. import com.teamtreehouse.stormy.R;
  26. import com.teamtreehouse.stormy.weather.Current;
  27. import com.teamtreehouse.stormy.weather.Day;
  28. import com.teamtreehouse.stormy.weather.Forecast;
  29. import com.teamtreehouse.stormy.weather.Hour;
  30.  
  31. import org.json.JSONArray;
  32. import org.json.JSONException;
  33. import org.json.JSONObject;
  34.  
  35. import java.io.IOException;
  36.  
  37. import butterknife.ButterKnife;
  38. import butterknife.InjectView;
  39.  
  40.  
  41. public class MainActivity extends ActionBarActivity {
  42.  
  43.     public static final String TAG = MainActivity.class.getSimpleName();
  44.  
  45.     private Forecast mForecast;
  46.  
  47.     @InjectView(R.id.timeLabel) TextView mTimeLabel;
  48.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  49.     @InjectView(R.id.humidityValue) TextView mHumidityValue;
  50.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  51.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  52.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  53.     @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  54.     @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  55.  
  56.     @Override
  57.     protected void onCreate(Bundle savedInstanceState) {
  58.         super.onCreate(savedInstanceState);
  59.         setContentView(R.layout.activity_main);
  60.         ButterKnife.inject(this);
  61.  
  62.         mProgressBar.setVisibility(View.INVISIBLE);
  63.  
  64.         final double latitude = 37.8267;
  65.         final double longitude = -122.423;
  66.  
  67.         mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  68.             @Override
  69.             public void onClick(View v) {
  70.                 getForecast(latitude, longitude);
  71.  
  72.             }
  73.         });
  74.  
  75.         getForecast(latitude, longitude);
  76.  
  77.         Log.d(TAG, "Main UI code is running!");
  78.     }
  79.  
  80.     private void getForecast(double latitude, double longitude) {
  81.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  82.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  83.                 "/" + latitude + "," + longitude;
  84.  
  85.         if (isNetworkAvailable()) {
  86.             toggleRefresh();
  87.  
  88.             OkHttpClient client = new OkHttpClient();
  89.             Request request = new Request.Builder().url(forecastUrl).build();
  90.  
  91.             Call call = client.newCall(request);
  92.             call.enqueue(new Callback() {
  93.                 @Override
  94.                 public void onFailure(Request request, IOException e) {
  95.                     runOnUiThread(new Runnable() {
  96.                         @Override
  97.                         public void run() {
  98.                             toggleRefresh();
  99.                         }
  100.                     });
  101.                     alertUserAboutError();
  102.                 }
  103.  
  104.                 @Override
  105.                 public void onResponse(Response response) throws IOException {
  106.                     runOnUiThread(new Runnable() {
  107.                         @Override
  108.                         public void run() {
  109.                             toggleRefresh();
  110.                         }
  111.                     });
  112.                     try {
  113.                         String jsonData = response.body().string();
  114.                         Log.v(TAG, jsonData);
  115.                         if (response.isSuccessful()) {
  116.                             mForecast = parseForecastDetails(jsonData);
  117.                             runOnUiThread(new Runnable() {
  118.                                 @Override
  119.                                 public void run() {
  120.                                     updateDisplay();
  121.                                 }
  122.                             });
  123.                         } else {
  124.                             alertUserAboutError();
  125.                         }
  126.                     } catch (IOException e) {
  127.                         Log.e(TAG, "Exception caught: ", e);
  128.                     } catch (JSONException e) {
  129.                         Log.e(TAG, "Exception caught: ", e);
  130.                     }
  131.                 }
  132.             });
  133.         }
  134.             else {
  135.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  136.         }
  137.     }
  138.  
  139.     private void toggleRefresh() {
  140.         if(mProgressBar.getVisibility() == View.INVISIBLE) {
  141.             mProgressBar.setVisibility(View.VISIBLE);
  142.             mRefreshImageView.setVisibility(View.INVISIBLE);
  143.         }
  144.         else {
  145.             mProgressBar.setVisibility(View.INVISIBLE);
  146.             mRefreshImageView.setVisibility(View.VISIBLE);
  147.         }
  148.     }
  149.  
  150.     private void updateDisplay() {
  151.         Current current = mForecast.getCurrent();
  152.  
  153.         mTemperatureLabel.setText(current.getTemperature() + "");
  154.         mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
  155.         mHumidityValue.setText(current.getHumidity() + "");
  156.         mPrecipValue.setText(current.getPrecipChance() + "%");
  157.         mSummaryLabel.setText(current.getSummary());
  158.  
  159.         Drawable drawable = getResources().getDrawable(current.getIconId());
  160.         mIconImageView.setImageDrawable(drawable);
  161.     }
  162.  
  163.     private Forecast parseForecastDetails(String jsonData) throws JSONException {
  164.         Forecast forecast = new Forecast();
  165.  
  166.         forecast.setCurrent(getCurrentDetails(jsonData));
  167.         forecast.setHourlyForecast(getHourlyForecast(jsonData));
  168.         forecast.setDailyForecast(getDailyForecast(jsonData));
  169.         return forecast;
  170.     }
  171.  
  172.     //For notes, see the private Hour[] below this one
  173.     private Day[] getDailyForecast(String jsonData) throws JSONException {
  174.         JSONObject forecast = new JSONObject(jsonData);
  175.         String timezone = forecast.getString("timezone");
  176.  
  177.         JSONObject daily = forecast.getJSONObject("daily");
  178.         JSONArray data = daily.getJSONArray("data");
  179.  
  180.         Day[] days = new Day[data.length()];
  181.         for (int i = 0; i < data.length(); i++) {
  182.             JSONObject jsonDay = data.getJSONObject(i);
  183.             Day day = new Day();
  184.  
  185.             day.setSummary(jsonDay.getString("summary"));
  186.             day.setIcon(jsonDay.getString("icon"));
  187.             day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
  188.             day.setTime(jsonDay.getLong("time"));
  189.             day.setTimezone(timezone);
  190.  
  191.             days[i] = day;
  192.         }
  193.             return days;
  194.  
  195.     }
  196.  
  197.     private Hour[] getHourlyForecast(String jsonData) throws JSONException {
  198.         JSONObject forecast = new JSONObject(jsonData);
  199.         String timezone = forecast.getString("timezone"); // [******]
  200.         JSONObject hourly = forecast.getJSONObject("hourly");
  201.         JSONArray data = hourly.getJSONArray("data");
  202.  
  203.         //Hopefully this is just review for you:
  204.         Hour [] hours = new Hour[data.length()];  //unlike for a regular Array, where its just .length, for JSONArray we need to call a method instead of accessing a property, thus .length()
  205.  
  206.         // Now we can loop through all the items in the JSONArray, get the data we want from each one, and set a new Hour object in the hours array.
  207.         for (int i = 0; i < data.length(); i++){ //test the int against the data.length and increment it by 1 each time
  208.             JSONObject jsonHour = data.getJSONObject(i);
  209.  
  210.             // Now that we have a JSONObject, we can use it to populate our model object, just like we see in our getCurrentDetails method below.
  211.             // So let's add a line and we'll create a new Hour variable to populate,
  212.             Hour hour = new Hour();  //Caution, make sure you have the Hour hour = new Hour(); above inside the for-loop, because if not, JAVA will just populate the array with the same object over and over again.
  213.             //And now we'll set all the values for this new object using the jsonHour object.
  214.             hour.setSummary(jsonHour.getString("summary")); // get the String data //pass in the "key"    // or should I say pass in the "key" to get the String data
  215.             hour.setTemperature(jsonHour.getDouble("temperature")); //get the Double data //pass in the "key"
  216.             hour.setIcon(jsonHour.getString("icon"));
  217.             hour.setTime(jsonHour.getLong("time"));
  218.             hour.setTimezone(timezone); // [******] // remember 'timezone' is not in a "string key" like the other ones
  219.  
  220.             //Now we need to store it in the array
  221.             hours[i] = hour;
  222.         }
  223.  
  224.         return hours;
  225.                                              //Now let's do the same thing with the DailyForecast
  226.     }
  227.  
  228.  
  229.  
  230.     private Current getCurrentDetails(String jsonData) throws JSONException {
  231.  
  232.         JSONObject forecast = new JSONObject(jsonData);
  233.         String timezone = forecast.getString("timezone");
  234.             Log.i(TAG, "From JSON: " + timezone);
  235.  
  236.         JSONObject currently = forecast.getJSONObject("currently");
  237.  
  238.         Current current = new Current();
  239.         current.setHumidity(currently.getDouble("humidity"));
  240.         current.setTime(currently.getLong("time"));
  241.         current.setIcon(currently.getString("icon"));
  242.         current.setPrecipChance(currently.getDouble("precipProbability"));
  243.         current.setSummary(currently.getString("summary"));
  244.         current.setTemperature(currently.getDouble("temperature"));
  245.         current.setTimeZone(timezone);
  246.  
  247.         Log.d(TAG, current.getFormattedTime());
  248.  
  249.         return current;
  250.     }
  251.  
  252.     private boolean isNetworkAvailable() {
  253.         ConnectivityManager manager = (ConnectivityManager)
  254.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  255.  
  256.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  257.         boolean isAvailable = false;
  258.         if (networkInfo != null && networkInfo.isConnected()) {
  259.             isAvailable = true;
  260.         }
  261.         return isAvailable;
  262.     }
  263.     private void alertUserAboutError() {
  264.         AlertDialogFragment dialog = new AlertDialogFragment();
  265.         dialog.show(getFragmentManager(), "error_dialog");
  266.     }
  267. }
  268.  
  269.  
  270. // https://teamtreehouse.com/library/android-lists-and-adapters/updating-the-data-model/introducing-jsonarray
  271. // https://teamtreehouse.com/library/android-lists-and-adapters/updating-the-data-model/from-jsonarray-to-a-java-array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement