Lesson 2: Connect Sunshine to the Cloud

Udacity – Developing Android Apps

Lesson 2 notes:

  • Open Weather Map
  • The URL query for 1 week forecast data at postal code 94043 using metric unit with JSON format.
    • api.openweathermap.org/data/2.5/forecast/daily?q=94043&units=metric&cnt=7&mode=json
    • default mode is json
  • HTTP request for weather
    • Make HTTP request
    • Read response from input stream
    • Clean up and log any errors
    • An example of the code to do this is here.
    • Tutorial for connecting to the network notes:
      • Choose an HTTP client
        • HttpURLConnection (Recommended)
        • HttpClient (Apache)
      • Check the Network Connection
        • getActiveNetworkInfo() or isConnected()
  • Logging
    • Log.e logs error messages
    • Avoid log spam
    • adb logcat at command line to view the debug and error messages. Additional option can be found here.
    • on Android Studio, you can launch Android Device Manager and select the device and click on logcat to view the same log messages.
    • Log level, Log._(String tag, String msg) with tag usually a constant defined for the name of the class or app
      • ERROR e – keep
      • WARN w- keep
      • INFO i- keep
      • DEBUG d- are compiled in but they are stripped out at run time.
      • VERBOSE v- should never compile into the app except for development
  • To enable auto import
    • Android Studio > Preferences > Editor > Auto Import. Check all the boxes and insert all imports on paste.
  • Threads
    • main thread aka UI thread that take care of all user input and output
    • background thread are use for long operation such as network call, decoding bitmap, or reading and writing from database.
    • Use AysncTask to fire off a new task from the UI thread. Here are 4 steps when the task is executed
      • onPreExecute() invoked on the UI thread for setup the task
      • doInBackground(Params…) invoked on the background thread for background computation and must be implemented.
      • onProgressUpdate(Progress…) invoked on the UI thread after a call to publishProgess(Progress…) to display any form of progress in the UI.
      • onPostExecute(Result) invoked by UI thread after background computation is finished.
  • Move to AsyncTask
    • Rename and Move ForecastFragment to a new file
      • To refactor the class name – right click on the class name > Refactor > Rename > type in new name
      • To move the class into its own file – select the class > Refactor > Move > select move up one level
    • Create AsyncTask called FetchWeatherTask
      • create public class FetchWeatherTask extends AsyncTask<Void, Void, Void> (Void mark the type not being used)
      • create method protected Void doInBackground(Void… params) and return null (null means return no parameter to UI threads after computation)
  • Why AsyncTask is not optimal
    • The transfer is on a thread whose lifetime is tied to a UI component so if the component is terminated, so does the transfer.
    • A better approach is to use a service with Inexact Alarm and SyncAdaptor
  • Menu options
    • in resource (res) folder > menu > main.xml file, there are single menu option for setting.
    • To add a menu option
      • add an item
      • define the id
      • add a title by referencing to a string you created
        • go to resource (res) > value > strings.xml and add a string
      • add app:showAsAction=”never” to show it in the overflow menu
    • in ForecastFragment.java ,model what the MainActivity.java
      • add onCreate method with setHasOptionsMenu(true)
      • add onCreateOptionsMenu() method
      • add onOptionsItemSelected() method using the id for action_refresh and add a new FetchweatherTask and execute it. However, at this point, the app crash due to SecurityException.
  • Permissions
    • each app is sandbox so no app can access information outside of its own VM.
    • permission to cross boundary is listed in the manifest.
    • a system app can be an intermediator for camera, phone call and accessing user-selected contact. However, getting user current location can only be done after declaring a user-permission in the manifest.
    • add internet Manifest.permission in the AndroidManifest.xml (e.g. android.permission.INTERNET.
  • Post Code Param
    • Modity FetchWeatherTask to take an argument of String
    • doInBackground method also receive a String as argument
    • Use Uri builder to build up the address
  • JSON
    • Using a JSON formatter to show that we need dt, main, max and min data for the apps.
    • Parsing the JSONObject to get the max temperature out
      • create String for list, temp, and max node.
      • create an JSONObject to store the Json string we got from the fetch.
      • create an JSONArray to get the list into an array of forecast by days.
      • create another JSONObject to grab only the forecast for the indexed day (0 base) from the JSONArray.
      • create another JSONObject to grab the temp node.
      • finally, grab the max node and return it as double.
    • Ensure doInBackground() returns String[]. This required to change AysncTask  and the return value of doInBackground.
  • Update the Adapter
    • override the AsyncTask onPostExecute method to add each day of forecast to the adapter.
    • adapter.notifyDatasetChanged() will notifies any attached observers that underlying data has changed.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s