Advertisement
yo2man

Making the refresh icon and progress bar

Jul 10th, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.50 KB | None | 0 0
  1. // Making the refresh icon and progress bar. Simple.
  2.  
  3. // android has a few different progress bars we can use to show that its loading
  4. // to align progressbar loading spinner with the refresh icon, go to properties >layout:alignComponent > click the reveal arrow > then set it by clicking on the blank space and a dropdown of images to align to will show.
  5.  
  6.  
  7. //--------------------------------------------------------------------
  8. MainActivity.java
  9.  
  10. package com.teamtreehouse.stormy;
  11.  
  12. import android.content.Context;
  13. import android.graphics.drawable.Drawable;
  14. import android.net.ConnectivityManager;
  15. import android.net.NetworkInfo;
  16. import android.support.v7.app.ActionBarActivity;
  17. import android.os.Bundle;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.widget.ImageView;
  21. import android.widget.ProgressBar;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24.  
  25. import com.squareup.okhttp.Call;
  26. import com.squareup.okhttp.Callback;
  27. import com.squareup.okhttp.OkHttpClient;
  28. import com.squareup.okhttp.Request;
  29. import com.squareup.okhttp.Response;
  30.  
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33.  
  34. import java.io.IOException;
  35.  
  36. import butterknife.ButterKnife;
  37. import butterknife.InjectView;
  38.  
  39.  
  40. public class MainActivity extends ActionBarActivity {
  41.  
  42.     public static final String TAG = MainActivity.class.getSimpleName();
  43.  
  44.     private CurrentWeather mCurrentWeather;
  45.  
  46.     @InjectView(R.id.timeLabel) TextView mTimeLabel; //doing it with butterknife annotation
  47.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  48.     @InjectView(R.id.humidityValue) TextView mHumidityValue;
  49.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  50.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  51.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  52.     @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  53.     @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  54.     //create new method to check for network connectivity
  55.  
  56.     @Override
  57.     protected void onCreate(Bundle savedInstanceState) {
  58.         super.onCreate(savedInstanceState);
  59.         setContentView(R.layout.activity_main);
  60.         ButterKnife.inject(this); //butterknife
  61.  
  62.         mProgressBar.setVisibility(View.INVISIBLE); // We can hide the loading progress bar here or in the xml. The tutorial guy just decided to do it here. *
  63.  
  64.         final double latitude = 37.8267; //cut and paste this two lines from below to up here so we can use them in method calls
  65.         final double longitude = -122.423;
  66.  
  67.         mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  68.             @Override
  69.             public void onClick(View v) {
  70.                 // We want to get a forecast just like we are in the OnCreate method.
  71.                 // Let's copy and paste everything to, no, I'm just kidding.
  72.                 // Let's refactor this code into a new method that we can use here and
  73.                 // on Create, and in the on click method.
  74.                 // Highlight everything from the API key to the bottom of the if else block> Right click on the highlighted>Extract>method > call it
  75.                 getForecast(latitude, longitude);
  76.  
  77.                 // If we we want to allow for different locations, we might want to provide latitude and longitude.
  78.             }
  79.         });
  80.  
  81.         getForecast(latitude, longitude);
  82.  
  83.         Log.d(TAG, "Main UI code is running!");
  84.     }
  85.  
  86.     //refactored and created the get Forecast method:
  87.     private void getForecast(double latitude, double longitude) { //We'll pass in the double latitude and the double longitude.
  88.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  89.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  90.                 "/" + latitude + "," + longitude;
  91.  
  92.         if (isNetworkAvailable()) {
  93.             toggleRefresh();
  94.  
  95.             OkHttpClient client = new OkHttpClient();
  96.             Request request = new Request.Builder().url(forecastUrl).build();
  97.  
  98.             Call call = client.newCall(request);
  99.             call.enqueue(new Callback() {
  100.                 @Override
  101.                 public void onFailure(Request request, IOException e) {
  102.                     //This is updating the main UI so we need to 'runOnUiThread' not a background thread. so surround 'toggleRefresh();' with runOnUiThread(new Runnable()){      }
  103.                     runOnUiThread(new Runnable(){
  104.                         @Override
  105.                         public void run(){
  106.                             toggleRefresh();
  107.                         }
  108.                     });
  109.                     alertUserAboutError();
  110.                 }
  111.  
  112.                 @Override
  113.                 public void onResponse(Response response) throws IOException {
  114.  
  115.                     //This is updating the UI so we need to 'runOnUiThread' not a background thread. so surround 'toggleRefresh();' with runOnUiThread(new Runnable()){      }
  116.                     runOnUiThread(new Runnable(){
  117.                         @Override
  118.                         public void run(){
  119.                             toggleRefresh();
  120.                         }
  121.                     });
  122.                     try {
  123.                         String jsonData = response.body().string();
  124.                         Log.v(TAG, jsonData);
  125.                         if (response.isSuccessful()) {
  126.                             mCurrentWeather = getCurrentDetails(jsonData);
  127.  
  128.                             //can't do it in background thread because only the main thread is allowed to update the UI like we stated before
  129.                             // What we need to do is send a message to the main UI thread that we have code ready for it.
  130.                             // We can do this a few different ways, but
  131.                             // we'll use a simple one using a special helper method called runOnUIThread.
  132.                             runOnUiThread(new Runnable() {
  133.                                 @Override
  134.                                 public void run() {
  135.                                     updateDisplay(); //create  a new method for update display instead of putting it here so code isn't messy
  136.                                 }
  137.                             });
  138.                         } else {
  139.                             alertUserAboutError();
  140.                         }
  141.                     } catch (IOException e) {
  142.                         Log.e(TAG, "Exception caught: ", e);
  143.                     } catch (JSONException e) {
  144.                         Log.e(TAG, "Exception caught: ", e);
  145.                     }
  146.                 }
  147.             });
  148.         }
  149.             else {
  150.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  151.         }
  152.     }
  153.  
  154.     private void toggleRefresh() {
  155.         // hide things if they are showing and show things if they are invisible
  156.         if(mProgressBar.getVisibility() == View.INVISIBLE) {
  157.             mProgressBar.setVisibility(View.VISIBLE); //make progress bar visible when refreshing *
  158.             mRefreshImageView.setVisibility(View.INVISIBLE); //make the refresh image invisible when normal *
  159.         }
  160.         else { //otherwise:
  161.             mProgressBar.setVisibility(View.INVISIBLE); //make progress bar invisible *
  162.             mRefreshImageView.setVisibility(View.VISIBLE); //make the refresh image visible *
  163.         }
  164.     }
  165.  
  166.     private void updateDisplay() {
  167.         mTemperatureLabel.setText(mCurrentWeather.getTemperature() + ""); // the temperature u get from .getTemperature is a 'Double' value thus you have to convert it to a string via + "" . simple.
  168.         mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
  169.         mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
  170.         mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
  171.         mSummaryLabel.setText(mCurrentWeather.getSummary());
  172.  
  173.         Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
  174.         mIconImageView.setImageDrawable(drawable);
  175.         //pretty simple stuff^
  176.     }
  177.  
  178.     private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
  179.  
  180.         JSONObject forecast = new JSONObject(jsonData);
  181.  
  182.         String timezone = forecast.getString("timezone");
  183.             Log.i(TAG, "From JSON: " + timezone);
  184.  
  185.         JSONObject currently = forecast.getJSONObject("currently");
  186.         CurrentWeather currentWeather = new CurrentWeather();
  187.         currentWeather.setHumidity(currently.getDouble("humidity"));
  188.         currentWeather.setTime(currently.getLong("time"));
  189.         currentWeather.setIcon(currently.getString("icon"));
  190.         currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
  191.         currentWeather.setSummary(currently.getString("summary"));
  192.         currentWeather.setTemperature(currently.getDouble("temperature"));
  193.         currentWeather.setTimeZone(timezone);
  194.  
  195.         Log.d(TAG, currentWeather.getFormattedTime());
  196.  
  197.         return currentWeather;
  198.  
  199.     }
  200.  
  201.     private boolean isNetworkAvailable() {
  202.         ConnectivityManager manager = (ConnectivityManager)
  203.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  204.  
  205.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  206.         boolean isAvailable = false;
  207.         if (networkInfo != null && networkInfo.isConnected()) {
  208.             isAvailable = true;
  209.         }
  210.         return isAvailable;
  211.     }
  212.     private void alertUserAboutError() {
  213.         AlertDialogFragment dialog = new AlertDialogFragment();
  214.         dialog.show(getFragmentManager(), "error_dialog");
  215.     }
  216. }
  217.  
  218.  
  219.  
  220.  
  221. //--------------------------------------------------------------------
  222. activity_main.xml
  223.  
  224. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  225.                 xmlns:tools="http://schemas.android.com/tools"
  226.                 android:layout_width="match_parent"
  227.                 android:layout_height="match_parent"
  228.                 android:paddingLeft="@dimen/activity_horizontal_margin"
  229.                 android:paddingRight="@dimen/activity_horizontal_margin"
  230.                 android:paddingTop="@dimen/activity_vertical_margin"
  231.                 android:paddingBottom="@dimen/activity_vertical_margin"
  232.                 tools:context=".MainActivity"
  233.                 android:background="#FFFC970b">
  234.  
  235.     <TextView
  236.         android:layout_width="wrap_content"
  237.         android:layout_height="wrap_content"
  238.         android:text="--"
  239.         android:id="@+id/temperatureLabel"
  240.         android:layout_centerVertical="true"
  241.         android:layout_centerHorizontal="true"
  242.         android:textColor="@android:color/white"
  243.         android:textSize="150sp"/>
  244.  
  245.     <ImageView
  246.         android:layout_width="wrap_content"
  247.         android:layout_height="wrap_content"
  248.         android:id="@+id/degreeImageView"
  249.         android:layout_alignTop="@+id/temperatureLabel"
  250.         android:layout_toRightOf="@+id/temperatureLabel"
  251.         android:layout_toEndOf="@+id/temperatureLabel"
  252.         android:src="@drawable/degree"
  253.         android:layout_marginTop="50dp"/>
  254.  
  255.     <TextView
  256.         android:layout_width="wrap_content"
  257.         android:layout_height="wrap_content"
  258.         android:text="..."
  259.         android:id="@+id/timeLabel"
  260.         android:layout_above="@+id/degreeImageView"
  261.         android:layout_centerHorizontal="true"
  262.         android:textColor="#80ffffff"
  263.         android:textSize="18sp"/>
  264.  
  265.     <TextView
  266.         android:layout_width="wrap_content"
  267.         android:layout_height="wrap_content"
  268.         android:text="Alcatraz Island, CA"
  269.         android:id="@+id/locationLabel"
  270.         android:layout_above="@+id/timeLabel"
  271.         android:layout_centerHorizontal="true"
  272.         android:layout_marginBottom="60dp"
  273.         android:textColor="@android:color/white"
  274.         android:textSize="24sp"/>
  275.  
  276.     <ImageView
  277.         android:layout_width="wrap_content"
  278.         android:layout_height="wrap_content"
  279.         android:id="@+id/iconImageView"
  280.         android:layout_alignBottom="@+id/locationLabel"
  281.         android:layout_alignParentLeft="true"
  282.         android:layout_alignParentStart="true"
  283.         android:src="@drawable/cloudy_night"/>
  284.  
  285.     <LinearLayout
  286.         android:orientation="horizontal"
  287.         android:layout_width="match_parent"
  288.         android:layout_height="wrap_content"
  289.         android:layout_below="@+id/temperatureLabel"
  290.         android:layout_centerHorizontal="true"
  291.         android:layout_marginTop="10dp"
  292.         android:weightSum="100"
  293.         android:id="@+id/linearLayout">
  294.  
  295.         <LinearLayout
  296.             android:orientation="vertical"
  297.             android:layout_width="wrap_content"
  298.             android:layout_height="match_parent"
  299.             android:layout_weight="50">
  300.  
  301.             <TextView
  302.                 android:layout_width="match_parent"
  303.                 android:layout_height="wrap_content"
  304.                 android:text="HUMIDITY"
  305.                 android:id="@+id/humidityLabel"
  306.                 android:textColor="#80FFFFFF"
  307.                 android:gravity="center_horizontal"/>
  308.  
  309.             <TextView
  310.                 android:layout_width="match_parent"
  311.                 android:layout_height="wrap_content"
  312.                 android:text="--"
  313.                 android:id="@+id/humidityValue"
  314.                 android:textColor="@android:color/white"
  315.                 android:textSize="24sp"
  316.                 android:gravity="center_horizontal"/>
  317.         </LinearLayout>
  318.  
  319.         <LinearLayout
  320.             android:orientation="vertical"
  321.             android:layout_width="wrap_content"
  322.             android:layout_height="match_parent"
  323.             android:layout_weight="50">
  324.  
  325.             <TextView
  326.                 android:layout_width="match_parent"
  327.                 android:layout_height="wrap_content"
  328.                 android:text="RAIN/SNOW?"
  329.                 android:id="@+id/precipLabel"
  330.                 android:textColor="#80ffffff"
  331.                 android:gravity="center_horizontal"/>
  332.  
  333.             <TextView
  334.                 android:layout_width="match_parent"
  335.                 android:layout_height="wrap_content"
  336.                 android:text="--"
  337.                 android:id="@+id/precipValue"
  338.                 android:textColor="@android:color/white"
  339.                 android:textSize="24sp"
  340.                 android:gravity="center_horizontal"/>
  341.         </LinearLayout>
  342.     </LinearLayout>
  343.  
  344.     <TextView
  345.         android:layout_width="wrap_content"
  346.         android:layout_height="wrap_content"
  347.         android:text="Getting current weather..."
  348.         android:id="@+id/summaryLabel"
  349.         android:layout_below="@+id/linearLayout"
  350.         android:layout_centerHorizontal="true"
  351.         android:layout_margin="40dp"
  352.         android:textColor="@android:color/white"
  353.         android:textSize="18sp"
  354.         android:gravity="center_horizontal"/>
  355.  
  356.     <ImageView
  357.         android:layout_width="wrap_content"
  358.         android:layout_height="wrap_content"
  359.         android:id="@+id/refreshImageView"
  360.         android:layout_alignParentTop="true"
  361.         android:layout_centerHorizontal="true"
  362.         android:src="@drawable/refresh"/>
  363.  
  364.     <ProgressBar
  365.         android:layout_width="wrap_content"
  366.         android:layout_height="wrap_content"
  367.         android:id="@+id/progressBar"
  368.         android:layout_alignParentTop="true"
  369.         android:layout_centerHorizontal="true"
  370.         android:layout_alignBottom="@+id/refreshImageView"/>
  371. </RelativeLayout>
  372.  
  373.  
  374. //https://teamtreehouse.com/library/build-a-weather-app/hooking-up-the-model-to-the-view/adding-a-refresh-button
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement