Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Introduction to ButterKnife for MVC
- // What a great interface, but it's useless right now.
- // We need to plug in the data we worked so hard to get from the forecast API.
- // Let's wire everything together in the controller of our MVC design,
- // boilerplate is the sections of code that have to be included in many places with little or no alteration. ie: Strings
- // We could declare member variables for the class and then set them in onCreate using FindViewByID. again and again and again, or we could:
- // use ButterKnife which makes writing boilerplate code easier (its an
- // http://www.thekeyconsultant.com/2013/09/5-reasons-you-should-use-butterknife.html
- // 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) >
- apply plugin: 'com.android.application'
- android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
- defaultConfig {
- applicationId "com.teamtreehouse.stormy"
- minSdkVersion 14
- targetSdkVersion 22
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- }
- dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- compile 'com.android.support:appcompat-v7:22.1.1'
- compile 'com.squareup.okhttp:okhttp:2.4.0'
- compile 'com.jakewharton:butterknife:6.0.0' // <-here
- }
- > then sync gradle.
- //------------------------------------------------------------------------------------------------------
- MainActivity.java
- package com.teamtreehouse.stormy;
- import android.content.Context;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.ImageView;
- 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 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 CurrentWeather mCurrentWeather;
- @InjectView(R.id.timeLabel) TextView mTimeLabel; //doing it with butterknife annotation
- @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
- @InjectView(R.id.humidityLabel) TextView mHumidityLabel;
- @InjectView(R.id.precipValue) TextView mPrecipValue;
- @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
- @InjectView(R.id.iconImageView)
- ImageView mIconImageView;
- //create new method to check for network connectivity
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.inject(this); //butterknife
- String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
- double latitude = 37.8267;
- double longitude = -122.423;
- String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
- "/" + latitude + "," + longitude;
- if (isNetworkAvailable()) {
- 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) {
- }
- @Override
- public void onResponse(Response response) throws IOException {
- try {
- String jsonData = response.body().string();
- Log.v(TAG,jsonData );
- if (response.isSuccessful()) {
- mCurrentWeather = getCurrentDetails(jsonData);
- } 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();
- }
- Log.d(TAG, "Main UI code is running!");
- }
- private CurrentWeather 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");
- CurrentWeather currentWeather = new CurrentWeather();
- currentWeather.setHumidity(currently.getDouble("humidity"));
- currentWeather.setTime(currently.getLong("time"));
- currentWeather.setIcon(currently.getString("icon"));
- currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
- currentWeather.setSummary(currently.getString("summary"));
- currentWeather.setTemperature(currently.getDouble("temperature"));
- currentWeather.setTimeZone(timezone);
- Log.d(TAG, currentWeather.getFormattedTime());
- return currentWeather;
- }
- 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/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