Advertisement
yo2man

Introducing ListViews and ListActivity and emptytextview

Jul 13th, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.77 KB | None | 0 0
  1. // Introducing ListActivity and Display data all or nothing
  2.  
  3.  
  4. //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:
  5.  
  6. DailyForecastActivity.Java
  7.  
  8. package com.teamtreehouse.stormy.UI;
  9.  
  10. import android.app.ListActivity;
  11. import android.support.v7.app.ActionBarActivity;
  12. import android.os.Bundle;
  13. import android.view.Menu;
  14. import android.view.MenuItem;
  15.  
  16. import com.teamtreehouse.stormy.R;
  17.  
  18. public class DailyForecastActivity extends ListActivity { //change 'ActionBarActivity' to 'ListActivity'
  19.  
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.activity_daily_forecast);
  24.  
  25.         // So our real data is going to be an array of dat objects with details about the weather
  26.         // 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
  27.         // This will illustrate how the main components of a ListView work.
  28.         // And then we can move onto more advanced uses.
  29.         String[] daysOfTheWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  30.  
  31.     }
  32. }
  33.  
  34. //---------------------------------------------------------------------------------------------
  35.  
  36. package com.teamtreehouse.stormy.UI;
  37.  
  38. import android.content.Context;
  39. import android.content.Intent;
  40. import android.graphics.drawable.Drawable;
  41. import android.net.ConnectivityManager;
  42. import android.net.NetworkInfo;
  43. import android.support.v7.app.ActionBarActivity;
  44. import android.os.Bundle;
  45. import android.util.Log;
  46. import android.view.View;
  47. import android.widget.ImageView;
  48. import android.widget.ProgressBar;
  49. import android.widget.TextView;
  50. import android.widget.Toast;
  51.  
  52. import com.squareup.okhttp.Call;
  53. import com.squareup.okhttp.Callback;
  54. import com.squareup.okhttp.OkHttpClient;
  55. import com.squareup.okhttp.Request;
  56. import com.squareup.okhttp.Response;
  57. import com.teamtreehouse.stormy.R;
  58. import com.teamtreehouse.stormy.weather.Current;
  59. import com.teamtreehouse.stormy.weather.Day;
  60. import com.teamtreehouse.stormy.weather.Forecast;
  61. import com.teamtreehouse.stormy.weather.Hour;
  62.  
  63. import org.json.JSONArray;
  64. import org.json.JSONException;
  65. import org.json.JSONObject;
  66.  
  67. import java.io.IOException;
  68.  
  69. import butterknife.ButterKnife;
  70. import butterknife.InjectView;
  71. import butterknife.OnClick;
  72.  
  73.  
  74. public class MainActivity extends ActionBarActivity {
  75.  
  76.     public static final String TAG = MainActivity.class.getSimpleName();
  77.  
  78.     private Forecast mForecast;
  79.  
  80.     @InjectView(R.id.timeLabel) TextView mTimeLabel;
  81.     @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  82.     @InjectView(R.id.humidityValue) TextView mHumidityValue;
  83.     @InjectView(R.id.precipValue) TextView mPrecipValue;
  84.     @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  85.     @InjectView(R.id.iconImageView) ImageView mIconImageView;
  86.     @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  87.     @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  88.  
  89.     @Override
  90.     protected void onCreate(Bundle savedInstanceState) {
  91.         super.onCreate(savedInstanceState);
  92.         setContentView(R.layout.activity_main);
  93.         ButterKnife.inject(this);
  94.  
  95.         mProgressBar.setVisibility(View.INVISIBLE);
  96.  
  97.         final double latitude = 37.8267;
  98.         final double longitude = -122.423;
  99.  
  100.         mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  101.             @Override
  102.             public void onClick(View v) {
  103.                 getForecast(latitude, longitude);
  104.  
  105.             }
  106.         });
  107.  
  108.         getForecast(latitude, longitude);
  109.  
  110.         Log.d(TAG, "Main UI code is running!");
  111.     }
  112.  
  113.     private void getForecast(double latitude, double longitude) {
  114.         String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
  115.         String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  116.                 "/" + latitude + "," + longitude;
  117.  
  118.         if (isNetworkAvailable()) {
  119.             toggleRefresh();
  120.  
  121.             OkHttpClient client = new OkHttpClient();
  122.             Request request = new Request.Builder().url(forecastUrl).build();
  123.  
  124.             Call call = client.newCall(request);
  125.             call.enqueue(new Callback() {
  126.                 @Override
  127.                 public void onFailure(Request request, IOException e) {
  128.                     runOnUiThread(new Runnable() {
  129.                         @Override
  130.                         public void run() {
  131.                             toggleRefresh();
  132.                         }
  133.                     });
  134.                     alertUserAboutError();
  135.                 }
  136.  
  137.                 @Override
  138.                 public void onResponse(Response response) throws IOException {
  139.                     runOnUiThread(new Runnable() {
  140.                         @Override
  141.                         public void run() {
  142.                             toggleRefresh();
  143.                         }
  144.                     });
  145.                     try {
  146.                         String jsonData = response.body().string();
  147.                         Log.v(TAG, jsonData);
  148.                         if (response.isSuccessful()) {
  149.                             mForecast = parseForecastDetails(jsonData);
  150.                             runOnUiThread(new Runnable() {
  151.                                 @Override
  152.                                 public void run() {
  153.                                     updateDisplay();
  154.                                 }
  155.                             });
  156.                         } else {
  157.                             alertUserAboutError();
  158.                         }
  159.                     } catch (IOException e) {
  160.                         Log.e(TAG, "Exception caught: ", e);
  161.                     } catch (JSONException e) {
  162.                         Log.e(TAG, "Exception caught: ", e);
  163.                     }
  164.                 }
  165.             });
  166.         }
  167.             else {
  168.                 Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
  169.         }
  170.     }
  171.  
  172.     private void toggleRefresh() {
  173.         if(mProgressBar.getVisibility() == View.INVISIBLE) {
  174.             mProgressBar.setVisibility(View.VISIBLE);
  175.             mRefreshImageView.setVisibility(View.INVISIBLE);
  176.         }
  177.         else {
  178.             mProgressBar.setVisibility(View.INVISIBLE);
  179.             mRefreshImageView.setVisibility(View.VISIBLE);
  180.         }
  181.     }
  182.  
  183.     private void updateDisplay() {
  184.         Current current = mForecast.getCurrent();
  185.  
  186.         mTemperatureLabel.setText(current.getTemperature() + "");
  187.         mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
  188.         mHumidityValue.setText(current.getHumidity() + "");
  189.         mPrecipValue.setText(current.getPrecipChance() + "%");
  190.         mSummaryLabel.setText(current.getSummary());
  191.  
  192.         Drawable drawable = getResources().getDrawable(current.getIconId());
  193.         mIconImageView.setImageDrawable(drawable);
  194.     }
  195.  
  196.     private Forecast parseForecastDetails(String jsonData) throws JSONException {
  197.         Forecast forecast = new Forecast();
  198.  
  199.         forecast.setCurrent(getCurrentDetails(jsonData));
  200.         forecast.setHourlyForecast(getHourlyForecast(jsonData));
  201.         forecast.setDailyForecast(getDailyForecast(jsonData));
  202.         return forecast;
  203.     }
  204.  
  205.     private Day[] getDailyForecast(String jsonData) throws JSONException {
  206.         JSONObject forecast = new JSONObject(jsonData);
  207.         String timezone = forecast.getString("timezone");
  208.  
  209.         JSONObject daily = forecast.getJSONObject("daily");
  210.         JSONArray data = daily.getJSONArray("data");
  211.  
  212.         Day[] days = new Day[data.length()];
  213.         for (int i = 0; i < data.length(); i++) {
  214.             JSONObject jsonDay = data.getJSONObject(i);
  215.             Day day = new Day();
  216.  
  217.             day.setSummary(jsonDay.getString("summary"));
  218.             day.setIcon(jsonDay.getString("icon"));
  219.             day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
  220.             day.setTime(jsonDay.getLong("time"));
  221.             day.setTimezone(timezone);
  222.  
  223.             days[i] = day;
  224.         }
  225.             return days;
  226.  
  227.     }
  228.  
  229.     private Hour[] getHourlyForecast(String jsonData) throws JSONException {
  230.         JSONObject forecast = new JSONObject(jsonData);
  231.         String timezone = forecast.getString("timezone");
  232.         JSONObject hourly = forecast.getJSONObject("hourly");
  233.         JSONArray data = hourly.getJSONArray("data");
  234.  
  235.         Hour [] hours = new Hour[data.length()];
  236.  
  237.         for (int i = 0; i < data.length(); i++){
  238.             JSONObject jsonHour = data.getJSONObject(i);
  239.  
  240.             Hour hour = new Hour();
  241.             hour.setSummary(jsonHour.getString("summary"));
  242.             hour.setTemperature(jsonHour.getDouble("temperature"));
  243.             hour.setIcon(jsonHour.getString("icon"));
  244.             hour.setTime(jsonHour.getLong("time"));
  245.             hour.setTimezone(timezone);
  246.  
  247.             hours[i] = hour;
  248.         }
  249.  
  250.         return hours;
  251.     }
  252.  
  253.  
  254.  
  255.     private Current getCurrentDetails(String jsonData) throws JSONException {
  256.  
  257.         JSONObject forecast = new JSONObject(jsonData);
  258.         String timezone = forecast.getString("timezone");
  259.             Log.i(TAG, "From JSON: " + timezone);
  260.  
  261.         JSONObject currently = forecast.getJSONObject("currently");
  262.  
  263.         Current current = new Current();
  264.         current.setHumidity(currently.getDouble("humidity"));
  265.         current.setTime(currently.getLong("time"));
  266.         current.setIcon(currently.getString("icon"));
  267.         current.setPrecipChance(currently.getDouble("precipProbability"));
  268.         current.setSummary(currently.getString("summary"));
  269.         current.setTemperature(currently.getDouble("temperature"));
  270.         current.setTimeZone(timezone);
  271.  
  272.         Log.d(TAG, current.getFormattedTime());
  273.  
  274.         return current;
  275.     }
  276.  
  277.     private boolean isNetworkAvailable() {
  278.         ConnectivityManager manager = (ConnectivityManager)
  279.                 getSystemService(Context.CONNECTIVITY_SERVICE);
  280.  
  281.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  282.         boolean isAvailable = false;
  283.         if (networkInfo != null && networkInfo.isConnected()) {
  284.             isAvailable = true;
  285.         }
  286.         return isAvailable;
  287.     }
  288.     private void alertUserAboutError() {
  289.         AlertDialogFragment dialog = new AlertDialogFragment();
  290.         dialog.show(getFragmentManager(), "error_dialog");
  291.     }
  292.  
  293.     //Add onClickListener for the button with butterknife instead of the old regular way
  294.     @OnClick (R.id.dailyButton)
  295.     public void startDailyActivity (View view){
  296.         Intent intent = new Intent(this, DailyForecastActivity.class);
  297.         startActivity(intent);
  298.  
  299.     }
  300. }
  301.  
  302. //-----------------------------------------------------------------------------------------
  303.  
  304. //Read from here FIRST then go back to the top.
  305. //Create a new activity for the DailyForecast
  306.  
  307. //Right click UI package> NEW> Blank Activity > give the name DailyForecastActivity to the activity> change Heirarchial parent with the[...] to MainActivity.
  308.  
  309. // to create listview
  310. // go to Designer Tab, under Containers, drag ListView to the screen until it aligns    android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
  311. //then make it match parent for both width and height.
  312.  
  313.  
  314. //Now we're actually going to change this ID to a special ID.
  315. // So, type along with me here, type @android:id/list.
  316. // This is a special ID that lets us use a special activity called list activity.
  317. // It makes working with lists a little bit easier.
  318. // Using a special system ID like this is what allows list activity to do some work for us automatically.
  319. activity_daily_forecast.xml
  320.  
  321. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  322.                 xmlns:tools="http://schemas.android.com/tools"
  323.                 android:layout_width="match_parent"
  324.                 android:layout_height="match_parent"
  325.                 android:paddingLeft="@dimen/activity_horizontal_margin"
  326.                 android:paddingRight="@dimen/activity_horizontal_margin"
  327.                 android:paddingTop="@dimen/activity_vertical_margin"
  328.                 android:paddingBottom="@dimen/activity_vertical_margin"
  329.                 tools:context="com.teamtreehouse.stormy.UI.DailyForecastActivity"
  330.                 android:background="@drawable/bg_gradient"
  331.                 >
  332.  
  333.     <ListView
  334.         android:layout_width="match_parent"
  335.         android:layout_height="match_parent"
  336.         android:id="@android:id/list"
  337.         android:layout_alignParentTop="true"
  338.         android:layout_alignParentLeft="true"
  339.         android:layout_alignParentStart="true"/>
  340.  
  341.     <!--empty text view that shows when ListView doesn't have any activity, brought to you specially by @android:id/list -->
  342.    <TextView
  343.        android:layout_width="wrap_content"
  344.        android:layout_height="wrap_content"
  345.        android:text="@string/no_daily_forecast_data"
  346.        android:id="@android:id/empty"   //<------- this is the Android system ID that sets this new TextView as the default empty view for the ListView.
  347.        android:layout_centerVertical="true"
  348.        android:layout_centerHorizontal="true"
  349.        android:textColor="#FFFFFFFF"/>
  350.  
  351. </RelativeLayout>
  352.  
  353.  
  354.  
  355. //-----------------------------------------------------------------------------
  356.  
  357.  
  358.  
  359.  
  360.  
  361.  
  362. // note to self: I am probably going to have to come back to this lesson for the contacts list of the FeedMe app
  363.  
  364.  
  365. // https://teamtreehouse.com/library/android-lists-and-adapters/standard-listviews/introducing-listview-and-listactivity
  366. // 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