Advertisement
yo2man

How to parse JSON data in weather app

Jul 8th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.57 KB | None | 0 0
  1. // How to parse JSON data in weather app
  2. //passing in JSON data key "timezone"
  3. //--------------------------------------------------------------
  4. MainActivity.java
  5.  
  6. package com.teamtreehouse.stormy;
  7.  
  8. import android.content.Context;
  9. import android.net.ConnectivityManager;
  10. import android.net.NetworkInfo;
  11. import android.support.v7.app.ActionBarActivity;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.widget.Toast;
  15.  
  16. import com.squareup.okhttp.Call;
  17. import com.squareup.okhttp.Callback;
  18. import com.squareup.okhttp.OkHttpClient;
  19. import com.squareup.okhttp.Request;
  20. import com.squareup.okhttp.Response;
  21.  
  22. import org.json.JSONException;
  23. import org.json.JSONObject;
  24.  
  25. import java.io.IOException;
  26.  
  27.  
  28. public class MainActivity extends ActionBarActivity {
  29.  
  30.     public static final String TAG = MainActivity.class.getSimpleName();
  31.  
  32.     private CurrentWeather mCurrentWeather; // CurrentWeather.java
  33.  
  34.     //create new method to check for network connectivity
  35.  
  36.     @Override
  37.     protected void onCreate(Bundle savedInstanceState) {
  38.         super.onCreate(savedInstanceState);
  39.         setContentView(R.layout.activity_main);
  40.  
  41.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  42.         double latitude = 37.8267;
  43.         double longitude = -122.423;
  44.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  45.                 "/" + latitude + "," + longitude;
  46.  
  47.         if (isNetworkAvailable()) {
  48.             OkHttpClient client = new OkHttpClient();
  49.             Request request = new Request.Builder().url(forecastUrl).build();
  50.  
  51.             Call call = client.newCall(request);
  52.             call.enqueue(new Callback() {
  53.                 @Override
  54.                 public void onFailure(Request request, IOException e) {
  55.  
  56.                 }
  57.  
  58.                 @Override
  59.                 public void onResponse(Response response) throws IOException {
  60.                     try {
  61.                         String jsonData = response.body().string(); //pass in Json Data as string*
  62.                         Log.v(TAG,jsonData ); // pass in (jsonData)*
  63.                         if (response.isSuccessful()) {
  64.                             mCurrentWeather = getCurrentDetails(jsonData); //if response is successful, set current weather  //(jsonData)* //[2]
  65.                         } else {
  66.                             alertUserAboutError();
  67.                         }
  68.                     }
  69.                     catch (IOException e) {
  70.                         Log.e(TAG, "Exception caught: ", e);
  71.                     }
  72.                     catch (JSONException e){ //[2]
  73.                         Log.e(TAG, "Exception caught: ", e);
  74.                     }
  75.                 }
  76.             });
  77.         }
  78.             else {
  79.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  80.         }
  81.  
  82.         Log.d(TAG, "Main UI code is running!");
  83.     }
  84.  
  85.     private CurrentWeather getCurrentDetails(String jsonData) throws JSONException { //this throws technique for handling exception is basically moving the responsibility of handling the exception to whomever calls this method[2]
  86.  
  87.         // We're gonna work with a special class called jsonObject. //JSONObject is a public method
  88.         // This class can hold any object represented in the json format, and its properties can be accessed using a few different methods.
  89.         JSONObject forecast = new JSONObject(jsonData); // The json object class has a constructor lets us pass in a string of jsonData to create a new JSON object
  90.  
  91.         // Access timezone info from JSON API https://api.forecast.io/forecast/d5faf0cb201f103df4dde0b8b0a4f490/37.8267,-122.423
  92.         String timezone = forecast.getString("timezone"); // pass in key from JSON: "timezone"
  93.             Log.i(TAG, "From JSON: " + timezone); // ^ log this
  94.  
  95.         return new CurrentWeather();
  96.  
  97.     }
  98.  
  99.     private boolean isNetworkAvailable() {
  100.         ConnectivityManager manager = (ConnectivityManager)
  101.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  102.  
  103.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  104.         boolean isAvailable = false;
  105.         if (networkInfo != null && networkInfo.isConnected()) {
  106.             isAvailable = true; //[**]
  107.         }
  108.         return isAvailable;
  109.     }
  110.     private void alertUserAboutError() {
  111.         AlertDialogFragment dialog = new AlertDialogFragment();
  112.         dialog.show(getFragmentManager(), "error_dialog");
  113.     }
  114. }
  115.  
  116. // https://teamtreehouse.com/library/build-a-weather-app/working-with-json/introducing-jsonobject   ?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement