Advertisement
yo2man

TreeHouse: What To Do When the Network is Down

Jul 7th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.91 KB | None | 0 0
  1. // TreeHouse: What To Do When the Network is Down
  2.  
  3. // Okay, we're doing a great job of getting data over the network, but
  4. // what happens when there is no network?
  5. // when we don't have a network connection,
  6. // a different exception is thrown and, of course, no data will be displayed.
  7. // For the user's sake,
  8. // we should check to see if the network is available before making the call.
  9. // If it isn't, let's show them a nice little message that says it's unavailable.
  10.  
  11. //------------------------------------------------------------------------------------------------
  12. MainActivity.java
  13.  
  14. package com.teamtreehouse.stormy;
  15.  
  16. import android.content.Context;
  17. import android.net.ConnectivityManager;
  18. import android.net.NetworkInfo;
  19. import android.support.v7.app.ActionBarActivity;
  20. import android.os.Bundle;
  21. import android.util.Log;
  22. import android.widget.Toast;
  23.  
  24. import com.squareup.okhttp.Call;
  25. import com.squareup.okhttp.Callback;
  26. import com.squareup.okhttp.OkHttpClient;
  27. import com.squareup.okhttp.Request;
  28. import com.squareup.okhttp.Response;
  29.  
  30. import java.io.IOException;
  31.  
  32.  
  33. public class MainActivity extends ActionBarActivity {
  34.  
  35.     public static final String TAG = MainActivity.class.getSimpleName();
  36.  
  37.     //create new method to check for network connectivity
  38.  
  39.     @Override
  40.     protected void onCreate(Bundle savedInstanceState) {
  41.         super.onCreate(savedInstanceState);
  42.         setContentView(R.layout.activity_main);
  43.  
  44.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  45.         double latitude = 37.8267;
  46.         double longitude = -122.423;
  47.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  48.                 "/" + latitude + "," + longitude;
  49.  
  50.         if (isNetworkAvailable()) {  // [**]   //create new method to check for network connectivity and wrap requesting HTTP in it.
  51.             OkHttpClient client = new OkHttpClient();
  52.             Request request = new Request.Builder().url(forecastUrl).build();
  53.  
  54.             Call call = client.newCall(request);
  55.             call.enqueue(new Callback() {
  56.                 @Override
  57.                 public void onFailure(Request request, IOException e) {
  58.  
  59.                 }
  60.  
  61.                 @Override
  62.                 public void onResponse(Response response) throws IOException {
  63.                     try {
  64.                         Log.v(TAG, response.body().string());
  65.                         if (response.isSuccessful()) {
  66.                         } else {
  67.                             alertUserAboutError();
  68.                         }
  69.                     } catch (IOException e) {
  70.                         Log.e(TAG, "Exception caught: ", e);
  71.                     }
  72.                 }
  73.             });
  74.         }
  75.             else { //[***if network unavailable]
  76.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show(); //extract String resource from "Network is unavailable!"
  77.         }
  78.  
  79.         Log.d(TAG, "Main UI code is running!");
  80.     }
  81.  
  82.     private boolean isNetworkAvailable() { // We'll set a return value based on the network availability. [**]
  83.         //We are going to use an Android Class called ConnectivityManager
  84.         ConnectivityManager manager = (ConnectivityManager)
  85.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  86.  
  87.         //  now we need to substantiate a NetworkInfo object. Lets call it 'networkInfo'
  88.         NetworkInfo networkInfo = manager.getActiveNetworkInfo(); //now we can analyze the network info to see if it is both present and active
  89.         // ^ to use .getActiveNetworkInfo method, we need to add another permission to manifest*
  90.  
  91.         boolean isAvailable = false;    //initialize boolean variable = is network present: true or false // Let's set it to false initially and then we'll only set it to true if the network is actually available.
  92.         if (networkInfo != null && networkInfo.isConnected()) { // check the network using an 'if' statement //if ("network is not null" aka network is present AND network is connected to the web)
  93.             isAvailable = true; //[**]
  94.         }
  95.         return isAvailable; //now we have a condition that will check if the network is presented and connected!!!!
  96.         // But what if this returns false?
  97.         // We should let the user know that the network is unavailable.
  98.         // Then they can check their network status, disable airplane mode. [***]
  99.     }
  100.     private void alertUserAboutError() {
  101.         AlertDialogFragment dialog = new AlertDialogFragment();
  102.         dialog.show(getFragmentManager(), "error_dialog");
  103.     }
  104. }
  105.  
  106.  
  107. //------------------------------------------------------------------------------------------------
  108.  
  109. AndroidManifest.xml
  110.  
  111. <?xml version="1.0" encoding="utf-8"?>
  112. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  113.     package="com.teamtreehouse.stormy" >
  114.  
  115.     <!--add this. It solves the MainNetwork Permission error by requesting permission to use the internet -->
  116.     <uses-permission android:name="android.permission.INTERNET"/>
  117.     <!--permission for getActiveNetwork method -->
  118.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  119.  
  120.     <application
  121.         android:allowBackup="true"
  122.         android:icon="@mipmap/ic_launcher"
  123.         android:label="@string/app_name"
  124.         android:theme="@style/AppTheme" >
  125.         <activity
  126.             android:name=".MainActivity"
  127.             android:label="@string/app_name" >
  128.             <intent-filter>
  129.                 <action android:name="android.intent.action.MAIN" />
  130.  
  131.                 <category android:name="android.intent.category.LAUNCHER" />
  132.             </intent-filter>
  133.         </activity>
  134.     </application>
  135.  
  136. </manifest>
  137. //------------------------------------------------------------------------------------------------
  138.  
  139.  
  140. // https://teamtreehouse.com/library/build-a-weather-app/concurrency-and-error-handling/what-to-do-when-the-network-is-down
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement