Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Formatting date / Importing and using image icons
- // now we want to add a new method to our model that gets the appropriate image
- // based on the icon value we are getting from the forecast API.
- // To get the image, we need to int ID that gets generated for each drawable resource.
- To import the image icons, download and extract them. Then copy the four drawable folders.
- Right click on res folder in android studio>show in explorer> click on res folder again> paste in the drawable folders
- //------------------------------------------------------------------------------------
- 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
- JSONObject currently = forecast.getJSONObject("currently"); //get JSONObject "currently" from forecast.api
- //^ And now from this JSONObject, we have all the data we need to create our current weather object :
- 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");
- }
- }
- //------------------------------------------------------------------------------------
- CurrentWeather.java
- package com.teamtreehouse.stormy;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.TimeZone;
- public class CurrentWeather {
- private String mIcon; // The Icon // it comes from Forecast API as a string, we convert it to an int
- private long mTime; //Time
- private double mTemperature; //Temp
- private double mHumidity; //humidity
- private double mPrecipChance; //chance of precipitation
- private String mSummary; //summary at the bottom
- private String mTimeZone;
- public String getTimeZone() {
- return mTimeZone;
- }
- public void setTimeZone(String timeZone) {
- mTimeZone = timeZone;
- }
- // Step 2: Generate getters and setters for everything: Code>Generate...>Getters and Setters:
- public double getHumidity() {
- return mHumidity;
- }
- public void setHumidity(double humidity) {
- mHumidity = humidity;
- }
- public String getIcon() {
- return mIcon;
- }
- // now we want to add a new method to our model that gets the appropriate image
- // based on the icon value we are getting from the forecast API.
- // To get the image, we need to int ID that gets generated for each drawable resource.
- public int getIconId(){
- // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
- int iconId = R.drawable.clear_day; //set this one in default, forecast api documentation says to "set a sensible icon as default"
- if(mIcon.equals("clear-day")){
- iconId = R.drawable.clear_day; //notice that the ids have _ compared to string "-" because we arent allowed to have dashes as resource names in Android Studio
- }
- else if (mIcon.equals("clear-night")){
- iconId = R.drawable.clear_night;
- }
- else if (mIcon.equals("rain")) {
- iconId = R.drawable.rain;
- }
- else if (mIcon.equals("snow")) {
- iconId = R.drawable.snow;
- }
- else if (mIcon.equals("sleet")) {
- iconId = R.drawable.sleet;
- }
- else if (mIcon.equals("wind")) {
- iconId = R.drawable.wind;
- }
- else if (mIcon.equals("fog")) {
- iconId = R.drawable.fog;
- }
- else if (mIcon.equals("cloudy")) {
- iconId = R.drawable.cloudy;
- }
- else if (mIcon.equals("partly-cloudy-day")) {
- iconId = R.drawable.partly_cloudy;
- }
- else if (mIcon.equals("partly-cloudy-night")) {
- iconId = R.drawable.cloudy_night;
- }
- return iconId;
- }
- public void setIcon(String icon) {
- mIcon = icon;
- }
- public double getPrecipChance() {
- return mPrecipChance;
- }
- public void setPrecipChance(double precipChance) {
- mPrecipChance = precipChance;
- }
- public String getSummary() {
- return mSummary;
- }
- public void setSummary(String summary) {
- mSummary = summary;
- }
- public double getTemperature() {
- return mTemperature;
- }
- public void setTemperature(double temperature) {
- mTemperature = temperature;
- }
- public long getTime() {
- return mTime;
- }
- public String getFormattedTime() {
- SimpleDateFormat formatter = new SimpleDateFormat("h:mm, a"); // this special Java called SimpleDateFormat converts unix date format to locale "normal" format
- formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); //set time zone, logging it from MainActivity
- Date dateTime = new Date(getTime() * 1000);
- String timeString = formatter.format(dateTime);
- return timeString;
- }
- public void setTime(long time) {
- mTime = time;
- }
- }
- //
- // https://teamtreehouse.com/library/build-a-weather-app/working-with-json/setting-currentweather-from-json
- // https://teamtreehouse.com/library/build-a-weather-app/working-with-json/cleaning-up-the-date-and-time
- // http://teamtreehouse.com/library/build-a-weather-app/working-with-json/setting-the-weather-icon
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement