Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //JSON Arrays
- // So far we've utilized the JSON object class to work with our JSON data.
- // Now we're going to look at the other important class for
- // JSON in Android, JSON array.
- /*
- Remember that JSON object is stored in two different ways:
- 1. A collection of key/value pairs grouped together into an object
- 2. An ordered list of object <--- this is the JSONArray
- */
- JSONObject and JSONArray image:
- http://content.screencast.com/users/yofu1234/folders/Jing/media/46242fcf-4b03-45e3-9e41-fee0d15483af/JSONArray%20and%20JSONObject.png
- Forecast Api JSON:
- data: [ <---this is the JSONarray data[]
- { <--- these are the JSONObjects{}
- "time": 1436665740,
- "precipIntensity": 0,
- "precipProbability": 0
- },
- {
- "time": 1436665800,
- "precipIntensity": 0,
- "precipProbability": 0
- },
- {
- "time": 1436665860,
- "precipIntensity": 0,
- "precipProbability": 0
- },
- // We will access this data array in code, and
- // then store each object in here as an array item using our new hour class.
- // Let's go back to our new method, parseForecastDetails.
- // Our forecast class has two arrays to fill so let's create two new methods to fill
- // them, following the format we used to fill the current weather data.
- package com.teamtreehouse.stormy.UI;
- import android.content.Context;
- import android.graphics.drawable.Drawable;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.squareup.okhttp.Call;
- import com.squareup.okhttp.Callback;
- import com.squareup.okhttp.OkHttpClient;
- import com.squareup.okhttp.Request;
- import com.squareup.okhttp.Response;
- import com.teamtreehouse.stormy.R;
- import com.teamtreehouse.stormy.weather.Current;
- import com.teamtreehouse.stormy.weather.Day;
- import com.teamtreehouse.stormy.weather.Forecast;
- import com.teamtreehouse.stormy.weather.Hour;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- import butterknife.ButterKnife;
- import butterknife.InjectView;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG = MainActivity.class.getSimpleName();
- private Forecast mForecast;
- @InjectView(R.id.timeLabel) TextView mTimeLabel;
- @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
- @InjectView(R.id.humidityValue) TextView mHumidityValue;
- @InjectView(R.id.precipValue) TextView mPrecipValue;
- @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
- @InjectView(R.id.iconImageView) ImageView mIconImageView;
- @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
- @InjectView(R.id.progressBar) ProgressBar mProgressBar;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.inject(this);
- mProgressBar.setVisibility(View.INVISIBLE);
- final double latitude = 37.8267;
- final double longitude = -122.423;
- mRefreshImageView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- getForecast(latitude, longitude);
- }
- });
- getForecast(latitude, longitude);
- Log.d(TAG, "Main UI code is running!");
- }
- private void getForecast(double latitude, double longitude) {
- String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
- String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
- "/" + latitude + "," + longitude;
- if (isNetworkAvailable()) {
- toggleRefresh();
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder().url(forecastUrl).build();
- Call call = client.newCall(request);
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Request request, IOException e) {
- runOnUiThread(new Runnable(){
- @Override
- public void run(){
- toggleRefresh();
- }
- });
- alertUserAboutError();
- }
- @Override
- public void onResponse(Response response) throws IOException {
- runOnUiThread(new Runnable(){
- @Override
- public void run(){
- toggleRefresh();
- }
- });
- try {
- String jsonData = response.body().string();
- Log.v(TAG, jsonData);
- if (response.isSuccessful()) {
- mForecast = parseForecastDetails(jsonData);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- updateDisplay();
- }
- });
- } else {
- alertUserAboutError();
- }
- } catch (IOException e) {
- Log.e(TAG, "Exception caught: ", e);
- } catch (JSONException e) {
- Log.e(TAG, "Exception caught: ", e);
- }
- }
- });
- }
- else {
- Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
- }
- }
- private void toggleRefresh() {
- if(mProgressBar.getVisibility() == View.INVISIBLE) {
- mProgressBar.setVisibility(View.VISIBLE);
- mRefreshImageView.setVisibility(View.INVISIBLE);
- }
- else {
- mProgressBar.setVisibility(View.INVISIBLE);
- mRefreshImageView.setVisibility(View.VISIBLE);
- }
- }
- private void updateDisplay() {
- Current current = mForecast.getCurrent();
- mTemperatureLabel.setText(current.getTemperature() + "");
- mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
- mHumidityValue.setText(current.getHumidity() + "");
- mPrecipValue.setText(current.getPrecipChance() + "%");
- mSummaryLabel.setText(current.getSummary());
- Drawable drawable = getResources().getDrawable(current.getIconId());
- mIconImageView.setImageDrawable(drawable);
- }
- private Forecast parseForecastDetails(String jsonData) throws JSONException {
- Forecast forecast = new Forecast();
- // Our forecast class has two Arrays to fill so let's create two new methods to fill
- // then, following the format we used to fill the current weather data.
- // We write the code we want, and then generate the new method declarations.
- forecast.setCurrent(getCurrentDetails(jsonData));
- 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. *
- 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 *
- return forecast;
- }
- private Day[] getDailyForecast(String jsonData) { //*
- return new Day[0];
- }
- private Hour[] getHourlyForecast(String jsonData) throws JSONException{ //*
- JSONObject forecast = new JSONObject(jsonData); //we want a JSONObject
- String timezone = forecast.getString("timezone"); //we also want to get the timezone
- JSONObject hourly = forecast.getJSONObject("hourly"); //[*3*] we'll name it hourly to match. Then we'll pass in the "hourly" key
- // ^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"}
- // Now that we have that object, we can access the array which is a property of that object
- JSONArray data = hourly.getJSONArray("data"); //pass in the key "data"
- // Okay, so we have an array of JSON objects, hooray.
- //But we want an array of our objects.
- // How should we go about converting them?
- /* JSON data from Forecast.api
- { <-- 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.
- "latitude": 37.8267,
- "longitude": -122.423,
- "timezone": "America/Los_Angeles",
- "offset": -7,
- currently: {...}
- minutely: {...}
- 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*]
- "summary": "Mostly cloudy throughout the day.",
- "icon": "partly-cloudy-night",
- "data":
- [
- {...}
- {...}
- {
- "time": 1436662800,
- "summary": "Partly Cloudy",
- "icon": "partly-cloudy-day",
- "precipIntensity": 0,
- "precipProbability": 0,
- "temperature": 65.39,
- "apparentTemperature": 65.39,
- "dewPoint": 53.82,
- "humidity": 0.66,
- "windSpeed": 13.04,
- "windBearing": 268,
- "visibility": 9.65,
- "cloudCover": 0.36,
- "pressure": 1014.91,
- "ozone": 327.73
- }
- */
- }
- private Current getCurrentDetails(String jsonData) throws JSONException {
- JSONObject forecast = new JSONObject(jsonData);
- String timezone = forecast.getString("timezone");
- Log.i(TAG, "From JSON: " + timezone);
- JSONObject currently = forecast.getJSONObject("currently");
- Current current = new Current();
- current.setHumidity(currently.getDouble("humidity"));
- current.setTime(currently.getLong("time"));
- current.setIcon(currently.getString("icon"));
- current.setPrecipChance(currently.getDouble("precipProbability"));
- current.setSummary(currently.getString("summary"));
- current.setTemperature(currently.getDouble("temperature"));
- current.setTimeZone(timezone);
- Log.d(TAG, current.getFormattedTime());
- return current;
- }
- private boolean isNetworkAvailable() {
- ConnectivityManager manager = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = manager.getActiveNetworkInfo();
- boolean isAvailable = false;
- if (networkInfo != null && networkInfo.isConnected()) {
- isAvailable = true;
- }
- return isAvailable;
- }
- private void alertUserAboutError() {
- AlertDialogFragment dialog = new AlertDialogFragment();
- dialog.show(getFragmentManager(), "error_dialog");
- }
- }
- // android documentation: http://developer.android.com/reference/org/json/JSONArray.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement