Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // How to parse JSON data in weather app
- //passing in JSON data key "timezone"
- //--------------------------------------------------------------
- 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.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;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG = MainActivity.class.getSimpleName();
- private CurrentWeather mCurrentWeather; // CurrentWeather.java
- //create new method to check for network connectivity
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- 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(); //pass in Json Data as string*
- Log.v(TAG,jsonData ); // pass in (jsonData)*
- if (response.isSuccessful()) {
- mCurrentWeather = getCurrentDetails(jsonData); //if response is successful, set current weather //(jsonData)* //[2]
- } else {
- alertUserAboutError();
- }
- }
- catch (IOException e) {
- Log.e(TAG, "Exception caught: ", e);
- }
- catch (JSONException e){ //[2]
- 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 { //this throws technique for handling exception is basically moving the responsibility of handling the exception to whomever calls this method[2]
- // We're gonna work with a special class called jsonObject. //JSONObject is a public method
- // This class can hold any object represented in the json format, and its properties can be accessed using a few different methods.
- 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
- // Access timezone info from JSON API https://api.forecast.io/forecast/d5faf0cb201f103df4dde0b8b0a4f490/37.8267,-122.423
- String timezone = forecast.getString("timezone"); // pass in key from JSON: "timezone"
- Log.i(TAG, "From JSON: " + timezone); // ^ log this
- return new 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/working-with-json/introducing-jsonobject ?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement