Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Introducing ListActivity and Display data all or nothing
- //this should be at the bottom of the paste but pastebin is bugging out in formatting when I put it there so I put in on the top. Read the Create a new Activity first then come back to this:
- DailyForecastActivity.Java
- package com.teamtreehouse.stormy.UI;
- import android.app.ListActivity;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.MenuItem;
- import com.teamtreehouse.stormy.R;
- public class DailyForecastActivity extends ListActivity { //change 'ActionBarActivity' to 'ListActivity'
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_daily_forecast);
- // So our real data is going to be an array of dat objects with details about the weather
- // but it takes a little more work so lets start with a mockup with an array of string where each item is simply a day of the week
- // This will illustrate how the main components of a ListView work.
- // And then we can move onto more advanced uses.
- String[] daysOfTheWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
- }
- }
- //---------------------------------------------------------------------------------------------
- package com.teamtreehouse.stormy.UI;
- import android.content.Context;
- import android.content.Intent;
- import android.graphics.drawable.Drawable;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
- 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 com.teamtreehouse.stormy.R;
- import com.teamtreehouse.stormy.weather.Current;
- import com.teamtreehouse.stormy.weather.Day;
- import com.teamtreehouse.stormy.weather.Forecast;
- import com.teamtreehouse.stormy.weather.Hour;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- import butterknife.ButterKnife;
- import butterknife.InjectView;
- import butterknife.OnClick;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG = MainActivity.class.getSimpleName();
- private Forecast mForecast;
- @InjectView(R.id.timeLabel) TextView mTimeLabel;
- @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
- @InjectView(R.id.humidityValue) TextView mHumidityValue;
- @InjectView(R.id.precipValue) TextView mPrecipValue;
- @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
- @InjectView(R.id.iconImageView) ImageView mIconImageView;
- @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
- @InjectView(R.id.progressBar) ProgressBar mProgressBar;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.inject(this);
- mProgressBar.setVisibility(View.INVISIBLE);
- final double latitude = 37.8267;
- final double longitude = -122.423;
- mRefreshImageView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- getForecast(latitude, longitude);
- }
- });
- getForecast(latitude, longitude);
- Log.d(TAG, "Main UI code is running!");
- }
- private void getForecast(double latitude, double longitude) {
- String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
- String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
- "/" + latitude + "," + longitude;
- if (isNetworkAvailable()) {
- toggleRefresh();
- 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) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- toggleRefresh();
- }
- });
- alertUserAboutError();
- }
- @Override
- public void onResponse(Response response) throws IOException {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- toggleRefresh();
- }
- });
- try {
- String jsonData = response.body().string();
- Log.v(TAG, jsonData);
- if (response.isSuccessful()) {
- mForecast = parseForecastDetails(jsonData);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- updateDisplay();
- }
- });
- } 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();
- }
- }
- private void toggleRefresh() {
- if(mProgressBar.getVisibility() == View.INVISIBLE) {
- mProgressBar.setVisibility(View.VISIBLE);
- mRefreshImageView.setVisibility(View.INVISIBLE);
- }
- else {
- mProgressBar.setVisibility(View.INVISIBLE);
- mRefreshImageView.setVisibility(View.VISIBLE);
- }
- }
- private void updateDisplay() {
- Current current = mForecast.getCurrent();
- mTemperatureLabel.setText(current.getTemperature() + "");
- mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
- mHumidityValue.setText(current.getHumidity() + "");
- mPrecipValue.setText(current.getPrecipChance() + "%");
- mSummaryLabel.setText(current.getSummary());
- Drawable drawable = getResources().getDrawable(current.getIconId());
- mIconImageView.setImageDrawable(drawable);
- }
- private Forecast parseForecastDetails(String jsonData) throws JSONException {
- Forecast forecast = new Forecast();
- forecast.setCurrent(getCurrentDetails(jsonData));
- forecast.setHourlyForecast(getHourlyForecast(jsonData));
- forecast.setDailyForecast(getDailyForecast(jsonData));
- return forecast;
- }
- private Day[] getDailyForecast(String jsonData) throws JSONException {
- JSONObject forecast = new JSONObject(jsonData);
- String timezone = forecast.getString("timezone");
- JSONObject daily = forecast.getJSONObject("daily");
- JSONArray data = daily.getJSONArray("data");
- Day[] days = new Day[data.length()];
- for (int i = 0; i < data.length(); i++) {
- JSONObject jsonDay = data.getJSONObject(i);
- Day day = new Day();
- day.setSummary(jsonDay.getString("summary"));
- day.setIcon(jsonDay.getString("icon"));
- day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
- day.setTime(jsonDay.getLong("time"));
- day.setTimezone(timezone);
- days[i] = day;
- }
- return days;
- }
- private Hour[] getHourlyForecast(String jsonData) throws JSONException {
- JSONObject forecast = new JSONObject(jsonData);
- String timezone = forecast.getString("timezone");
- JSONObject hourly = forecast.getJSONObject("hourly");
- JSONArray data = hourly.getJSONArray("data");
- Hour [] hours = new Hour[data.length()];
- for (int i = 0; i < data.length(); i++){
- JSONObject jsonHour = data.getJSONObject(i);
- Hour hour = new Hour();
- hour.setSummary(jsonHour.getString("summary"));
- hour.setTemperature(jsonHour.getDouble("temperature"));
- hour.setIcon(jsonHour.getString("icon"));
- hour.setTime(jsonHour.getLong("time"));
- hour.setTimezone(timezone);
- hours[i] = hour;
- }
- return hours;
- }
- private Current 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");
- Current current = new Current();
- current.setHumidity(currently.getDouble("humidity"));
- current.setTime(currently.getLong("time"));
- current.setIcon(currently.getString("icon"));
- current.setPrecipChance(currently.getDouble("precipProbability"));
- current.setSummary(currently.getString("summary"));
- current.setTemperature(currently.getDouble("temperature"));
- current.setTimeZone(timezone);
- Log.d(TAG, current.getFormattedTime());
- return current;
- }
- 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");
- }
- //Add onClickListener for the button with butterknife instead of the old regular way
- @OnClick (R.id.dailyButton)
- public void startDailyActivity (View view){
- Intent intent = new Intent(this, DailyForecastActivity.class);
- startActivity(intent);
- }
- }
- //-----------------------------------------------------------------------------------------
- //Read from here FIRST then go back to the top.
- //Create a new activity for the DailyForecast
- //Right click UI package> NEW> Blank Activity > give the name DailyForecastActivity to the activity> change Heirarchial parent with the[...] to MainActivity.
- // to create listview
- // go to Designer Tab, under Containers, drag ListView to the screen until it aligns android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
- //then make it match parent for both width and height.
- //Now we're actually going to change this ID to a special ID.
- // So, type along with me here, type @android:id/list.
- // This is a special ID that lets us use a special activity called list activity.
- // It makes working with lists a little bit easier.
- // Using a special system ID like this is what allows list activity to do some work for us automatically.
- activity_daily_forecast.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin"
- tools:context="com.teamtreehouse.stormy.UI.DailyForecastActivity"
- android:background="@drawable/bg_gradient"
- >
- <ListView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@android:id/list"
- android:layout_alignParentTop="true"
- android:layout_alignParentLeft="true"
- android:layout_alignParentStart="true"/>
- <!--empty text view that shows when ListView doesn't have any activity, brought to you specially by @android:id/list -->
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/no_daily_forecast_data"
- android:id="@android:id/empty" //<------- this is the Android system ID that sets this new TextView as the default empty view for the ListView.
- android:layout_centerVertical="true"
- android:layout_centerHorizontal="true"
- android:textColor="#FFFFFFFF"/>
- </RelativeLayout>
- //-----------------------------------------------------------------------------
- // note to self: I am probably going to have to come back to this lesson for the contacts list of the FeedMe app
- // https://teamtreehouse.com/library/android-lists-and-adapters/standard-listviews/introducing-listview-and-listactivity
- // https://teamtreehouse.com/library/android-lists-and-adapters/standard-listviews/displaying-list-data-or-none-at-all
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement