Advertisement
yo2man

Introduction to ButterKnife for MVC

Jul 9th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.55 KB | None | 0 0
  1. //Introduction to ButterKnife for MVC
  2.  
  3. // What a great interface, but it's useless right now.
  4. // We need to plug in the data we worked so hard to get from the forecast API.
  5. // Let's wire everything together in the controller of our MVC design,
  6.  
  7. // boilerplate is the sections of code that have to be included in many places with little or no alteration.  ie: Strings
  8.  
  9. // We could declare member variables for the class and then set them in onCreate using FindViewByID. again and again and again, or we could:
  10. // use ButterKnife which makes writing boilerplate code easier (its an
  11. // http://www.thekeyconsultant.com/2013/09/5-reasons-you-should-use-butterknife.html
  12.  
  13.  
  14. // to get butterknife: go to github page: https://github.com/JakeWharton/butterknife scroll down the readme and copy the compile: code > Go back to android studio > Gradle Scripts > build.gradle(Module: app) >
  15.  
  16. apply plugin: 'com.android.application'
  17.  
  18. android {
  19.     compileSdkVersion 22
  20.     buildToolsVersion "22.0.1"
  21.  
  22.     defaultConfig {
  23.         applicationId "com.teamtreehouse.stormy"
  24.         minSdkVersion 14
  25.         targetSdkVersion 22
  26.         versionCode 1
  27.         versionName "1.0"
  28.     }
  29.     buildTypes {
  30.         release {
  31.             minifyEnabled false
  32.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  33.         }
  34.     }
  35. }
  36.  
  37. dependencies {
  38.     compile fileTree(dir: 'libs', include: ['*.jar'])
  39.     compile 'com.android.support:appcompat-v7:22.1.1'
  40.     compile 'com.squareup.okhttp:okhttp:2.4.0'
  41.     compile 'com.jakewharton:butterknife:6.0.0'  // <-here
  42. }
  43.  
  44. > then sync gradle.
  45.  
  46. //------------------------------------------------------------------------------------------------------
  47. MainActivity.java
  48.  
  49. package com.teamtreehouse.stormy;
  50.  
  51. import android.content.Context;
  52. import android.net.ConnectivityManager;
  53. import android.net.NetworkInfo;
  54. import android.support.v7.app.ActionBarActivity;
  55. import android.os.Bundle;
  56. import android.util.Log;
  57. import android.widget.ImageView;
  58. import android.widget.TextView;
  59. import android.widget.Toast;
  60.  
  61. import com.squareup.okhttp.Call;
  62. import com.squareup.okhttp.Callback;
  63. import com.squareup.okhttp.OkHttpClient;
  64. import com.squareup.okhttp.Request;
  65. import com.squareup.okhttp.Response;
  66.  
  67. import org.json.JSONException;
  68. import org.json.JSONObject;
  69.  
  70. import java.io.IOException;
  71.  
  72. import butterknife.ButterKnife;
  73. import butterknife.InjectView;
  74.  
  75.  
  76. public class MainActivity extends ActionBarActivity {
  77.  
  78.     public static final String TAG = MainActivity.class.getSimpleName();
  79.  
  80.     private CurrentWeather mCurrentWeather;
  81.  
  82.     @InjectView(R.id.timeLabel) TextView mTimeLabel; //doing it with butterknife annotation
  83.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  84.     @InjectView(R.id.humidityLabel) TextView mHumidityLabel;
  85.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  86.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  87.     @InjectView(R.id.iconImageView)
  88.     ImageView mIconImageView;
  89.     //create new method to check for network connectivity
  90.  
  91.     @Override
  92.     protected void onCreate(Bundle savedInstanceState) {
  93.         super.onCreate(savedInstanceState);
  94.         setContentView(R.layout.activity_main);
  95.         ButterKnife.inject(this); //butterknife
  96.  
  97.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  98.         double latitude = 37.8267;
  99.         double longitude = -122.423;
  100.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  101.                 "/" + latitude + "," + longitude;
  102.  
  103.         if (isNetworkAvailable()) {
  104.             OkHttpClient client = new OkHttpClient();
  105.             Request request = new Request.Builder().url(forecastUrl).build();
  106.  
  107.             Call call = client.newCall(request);
  108.             call.enqueue(new Callback() {
  109.                 @Override
  110.                 public void onFailure(Request request, IOException e) {
  111.  
  112.                 }
  113.  
  114.                 @Override
  115.                 public void onResponse(Response response) throws IOException {
  116.                     try {
  117.                         String jsonData = response.body().string();
  118.                         Log.v(TAG,jsonData );
  119.                         if (response.isSuccessful()) {
  120.                             mCurrentWeather = getCurrentDetails(jsonData);
  121.                         } else {
  122.                             alertUserAboutError();
  123.                         }
  124.                     }
  125.                     catch (IOException e) {
  126.                         Log.e(TAG, "Exception caught: ", e);
  127.                     }
  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.         Log.d(TAG, "Main UI code is running!");
  139.     }
  140.  
  141.     private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
  142.  
  143.         JSONObject forecast = new JSONObject(jsonData);
  144.  
  145.         String timezone = forecast.getString("timezone");
  146.             Log.i(TAG, "From JSON: " + timezone);
  147.  
  148.         JSONObject currently = forecast.getJSONObject("currently");
  149.         CurrentWeather currentWeather = new CurrentWeather();
  150.         currentWeather.setHumidity(currently.getDouble("humidity"));
  151.         currentWeather.setTime(currently.getLong("time"));
  152.         currentWeather.setIcon(currently.getString("icon"));
  153.         currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
  154.         currentWeather.setSummary(currently.getString("summary"));
  155.         currentWeather.setTemperature(currently.getDouble("temperature"));
  156.         currentWeather.setTimeZone(timezone);
  157.  
  158.         Log.d(TAG, currentWeather.getFormattedTime());
  159.  
  160.         return currentWeather;
  161.  
  162.     }
  163.  
  164.     private boolean isNetworkAvailable() {
  165.         ConnectivityManager manager = (ConnectivityManager)
  166.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  167.  
  168.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  169.         boolean isAvailable = false;
  170.         if (networkInfo != null && networkInfo.isConnected()) {
  171.             isAvailable = true;
  172.         }
  173.         return isAvailable;
  174.     }
  175.     private void alertUserAboutError() {
  176.         AlertDialogFragment dialog = new AlertDialogFragment();
  177.         dialog.show(getFragmentManager(), "error_dialog");
  178.     }
  179. }
  180.  
  181.  
  182. // https://teamtreehouse.com/library/build-a-weather-app/hooking-up-the-model-to-the-view/using-butter-knife-for-views
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement