Advertisement
yo2man

Replacing 'Current' variable with 'Forecast' variable

Jul 11th, 2015
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.30 KB | None | 0 0
  1. // Replacing 'Current' variable with 'Forecast' variable, Don't really know why
  2.  
  3. package com.teamtreehouse.stormy.UI;
  4.  
  5. import android.content.Context;
  6. import android.graphics.drawable.Drawable;
  7. import android.net.ConnectivityManager;
  8. import android.net.NetworkInfo;
  9. import android.support.v7.app.ActionBarActivity;
  10. import android.os.Bundle;
  11. import android.util.Log;
  12. import android.view.View;
  13. import android.widget.ImageView;
  14. import android.widget.ProgressBar;
  15. import android.widget.TextView;
  16. import android.widget.Toast;
  17.  
  18. import com.squareup.okhttp.Call;
  19. import com.squareup.okhttp.Callback;
  20. import com.squareup.okhttp.OkHttpClient;
  21. import com.squareup.okhttp.Request;
  22. import com.squareup.okhttp.Response;
  23. import com.teamtreehouse.stormy.R;
  24. import com.teamtreehouse.stormy.weather.Current;
  25. import com.teamtreehouse.stormy.weather.Forecast;
  26.  
  27. import org.json.JSONException;
  28. import org.json.JSONObject;
  29.  
  30. import java.io.IOException;
  31.  
  32. import butterknife.ButterKnife;
  33. import butterknife.InjectView;
  34.  
  35.  
  36. public class MainActivity extends ActionBarActivity {
  37.  
  38.     public static final String TAG = MainActivity.class.getSimpleName();
  39.  
  40.     private Forecast mForecast; //replace Current variable with Forecast variable.
  41.  
  42.     @InjectView(R.id.timeLabel) TextView mTimeLabel;
  43.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  44.     @InjectView(R.id.humidityValue) TextView mHumidityValue;
  45.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  46.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  47.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  48.     @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  49.     @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  50.  
  51.     @Override
  52.     protected void onCreate(Bundle savedInstanceState) {
  53.         super.onCreate(savedInstanceState);
  54.         setContentView(R.layout.activity_main);
  55.         ButterKnife.inject(this);
  56.  
  57.         mProgressBar.setVisibility(View.INVISIBLE);
  58.  
  59.         final double latitude = 37.8267;
  60.         final double longitude = -122.423;
  61.  
  62.         mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  63.             @Override
  64.             public void onClick(View v) {
  65.                 getForecast(latitude, longitude);
  66.  
  67.             }
  68.         });
  69.  
  70.         getForecast(latitude, longitude);
  71.  
  72.         Log.d(TAG, "Main UI code is running!");
  73.     }
  74.  
  75.     private void getForecast(double latitude, double longitude) {
  76.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  77.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  78.                 "/" + latitude + "," + longitude;
  79.  
  80.         if (isNetworkAvailable()) {
  81.             toggleRefresh();
  82.  
  83.             OkHttpClient client = new OkHttpClient();
  84.             Request request = new Request.Builder().url(forecastUrl).build();
  85.  
  86.             Call call = client.newCall(request);
  87.             call.enqueue(new Callback() {
  88.                 @Override
  89.                 public void onFailure(Request request, IOException e) {
  90.                     runOnUiThread(new Runnable(){
  91.                         @Override
  92.                         public void run(){
  93.                             toggleRefresh();
  94.                         }
  95.                     });
  96.                     alertUserAboutError();
  97.                 }
  98.  
  99.                 @Override
  100.                 public void onResponse(Response response) throws IOException {
  101.                     runOnUiThread(new Runnable(){
  102.                         @Override
  103.                         public void run(){
  104.                             toggleRefresh();
  105.                         }
  106.                     });
  107.                     try {
  108.                         String jsonData = response.body().string();
  109.                         Log.v(TAG, jsonData);
  110.                         if (response.isSuccessful()) {
  111.                             mForecast = parseForecastDetails(jsonData); // replaced - > mCurrent = getCurrentDetails(jsonData);
  112.                             runOnUiThread(new Runnable() {
  113.                                 @Override
  114.                                 public void run() {
  115.                                     updateDisplay();
  116.                                 }
  117.                             });
  118.                         } else {
  119.                             alertUserAboutError();
  120.                         }
  121.                     } catch (IOException e) {
  122.                         Log.e(TAG, "Exception caught: ", e);
  123.                     } catch (JSONException e) {
  124.                         Log.e(TAG, "Exception caught: ", e);
  125.                     }
  126.                 }
  127.             });
  128.         }
  129.             else {
  130.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  131.         }
  132.     }
  133.  
  134.     private void toggleRefresh() {
  135.         if(mProgressBar.getVisibility() == View.INVISIBLE) {
  136.             mProgressBar.setVisibility(View.VISIBLE);
  137.             mRefreshImageView.setVisibility(View.INVISIBLE);
  138.         }
  139.         else {
  140.             mProgressBar.setVisibility(View.INVISIBLE);
  141.             mRefreshImageView.setVisibility(View.VISIBLE);
  142.         }
  143.     }
  144.  
  145.     private void updateDisplay() {
  146.         Current current = mForecast.getCurrent(); // add this line then replace all 'mCurrent' with 'current' below
  147.  
  148.         mTemperatureLabel.setText(current.getTemperature() + ""); // the temperature u get from .getTemperature is a 'Double' value thus you have to convert it to a string via + "" . simple.
  149.         mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
  150.         mHumidityValue.setText(current.getHumidity() + "");
  151.         mPrecipValue.setText(current.getPrecipChance() + "%");
  152.         mSummaryLabel.setText(current.getSummary());
  153.  
  154.         Drawable drawable = getResources().getDrawable(current.getIconId());
  155.         mIconImageView.setImageDrawable(drawable);
  156.         //pretty simple stuff^
  157.     }
  158.  
  159.     // Add another method for 'Forecast' object in addition to the 'Current' object we already created
  160.     private Forecast parseForecastDetails(String jsonData) throws JSONException  {
  161.         Forecast forecast = new Forecast();
  162.  
  163.         // here we want to set the current property for
  164.         // forecast using forecast.setCurrent,
  165.         // and now we can just call getCurrentDetails.
  166.         // And we can pass along the same jsonData
  167.         // object since it's just the entire string of JSON data.
  168.         forecast.setCurrent(getCurrentDetails(jsonData));
  169.  
  170.         return forecast;
  171.     }
  172.  
  173.     private Current getCurrentDetails(String jsonData) throws JSONException {
  174.  
  175.         //Okay, so the code in here is using the JSONObject class to convert the string of
  176.         // JSON data received from the API into a Java object that we can access and
  177.         // manipulate in our code.
  178.         JSONObject forecast = new JSONObject(jsonData);
  179.         String timezone = forecast.getString("timezone");
  180.             Log.i(TAG, "From JSON: " + timezone);
  181.  
  182.         JSONObject currently = forecast.getJSONObject("currently");
  183.  
  184.         //We are filling up the 'Current' model object here:
  185.         Current current = new Current();
  186.         current.setHumidity(currently.getDouble("humidity"));
  187.         current.setTime(currently.getLong("time"));
  188.         current.setIcon(currently.getString("icon"));
  189.         current.setPrecipChance(currently.getDouble("precipProbability"));
  190.         current.setSummary(currently.getString("summary"));
  191.         current.setTemperature(currently.getDouble("temperature"));
  192.         current.setTimeZone(timezone);
  193.  
  194.         Log.d(TAG, current.getFormattedTime());
  195.  
  196.         return current;
  197.  
  198.     }
  199.  
  200.     private boolean isNetworkAvailable() {
  201.         ConnectivityManager manager = (ConnectivityManager)
  202.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  203.  
  204.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  205.         boolean isAvailable = false;
  206.         if (networkInfo != null && networkInfo.isConnected()) {
  207.             isAvailable = true;
  208.         }
  209.         return isAvailable;
  210.     }
  211.     private void alertUserAboutError() {
  212.         AlertDialogFragment dialog = new AlertDialogFragment();
  213.         dialog.show(getFragmentManager(), "error_dialog");
  214.     }
  215. }
  216.  
  217.  
  218. // https://teamtreehouse.com/library/android-lists-and-adapters/updating-the-data-model/getting-the-whole-forecast
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement