Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Replacing 'Current' variable with 'Forecast' variable, Don't really know why
- 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.Forecast;
- 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; //replace Current variable with Forecast variable.
- @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); // replaced - > mCurrent = getCurrentDetails(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(); // add this line then replace all 'mCurrent' with 'current' below
- 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.
- 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);
- //pretty simple stuff^
- }
- // Add another method for 'Forecast' object in addition to the 'Current' object we already created
- private Forecast parseForecastDetails(String jsonData) throws JSONException {
- Forecast forecast = new Forecast();
- // here we want to set the current property for
- // forecast using forecast.setCurrent,
- // and now we can just call getCurrentDetails.
- // And we can pass along the same jsonData
- // object since it's just the entire string of JSON data.
- forecast.setCurrent(getCurrentDetails(jsonData));
- return forecast;
- }
- private Current getCurrentDetails(String jsonData) throws JSONException {
- //Okay, so the code in here is using the JSONObject class to convert the string of
- // JSON data received from the API into a Java object that we can access and
- // manipulate in our code.
- JSONObject forecast = new JSONObject(jsonData);
- String timezone = forecast.getString("timezone");
- Log.i(TAG, "From JSON: " + timezone);
- JSONObject currently = forecast.getJSONObject("currently");
- //We are filling up the 'Current' model object here:
- 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");
- }
- }
- // 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