Appendix: Homework
Contents:
- 1.1 Creating a Fragment with a UI
- 1.2: Communicating with a Fragment
- 2.1: Building app widgets
- 3.1: Working with sensor data
- 3.2: Working with sensor-based orientation
- 4.0 Optimizing for performance
- 4.1 Analyzing rendering and layout
- 4.2 Using the Memory Profiler
- 4.3 Optimizing network, battery, and image use
- 5.1 Using resources for languages
- 5.2 Using the locale
- 6.1: Exploring accessibility in Android
- 6.2: Creating accessible apps
- 7.1: Using the device location
- 8.1: Using the Places API
- 9.1 Adding a Google Map to your app
- 10.1 Creating a custom view
- 11.1 Applying clipping to a Canvas object
- 11.2 Creating a SurfaceView object
- 12.1 Creating animations
- 13.1 Simple media playback
- 14.1: Working with Architecture Components: Room, LiveData, ViewModel
- 14.2: Working with Architecture Components: Deleting and updating data
This appendix lists possible homework assignments that students can complete at the end of each practical. It is the instructor's responsibility to do the following:
- Assign homework, if homework is required.
- Communicate to students how to submit homework assignments.
- Grade homework assignments.
Instructors can use these suggested assignments as little or as much as they want. Instructors should feel free to assign any other homework they feel is appropriate.
1.1: Creating a Fragment with a UI
Build and run an app
Build an app that uses the same fragment ( SimpleFragment
) with more than one activity.
- In Android Studio, open the FragmentExample2 app.
- Add another Empty Activity called
SecondActivity
. ForSecondActivity
, use the same layout asMainActivity
. - In the
SecondActivity
layout, replace thearticle1
string resource witharticle2
. Replace thetitle1
string resource withtitle2
. Both string resources are provided in the starter app and included in FragmentExample2.
Add the following functionality to the app, using SimpleFragment
with SecondActivity
:
- Add a Next button under the Open button to navigate from the first activity to the second activity.
- Add a Previous button in the second activity to navigate back to the first activity.
Answer these questions
Question 1
Which subclass of Fragment
displays a vertical list of items that are managed by an adapter?
RowsFragment()
PreferenceFragment()
DialogFragment()
ListFragment()
Question 2
Which of the following is the best sequence for adding a fragment to an activity that is already running?
- Declare the fragment inside the activity's layout file using a
<fragment>
view. - Declare a location for the fragment inside the activity's layout file using the
<FrameLayout>
view group. - Declare the location for the fragment inside the activity's layout file using the
<FrameLayout>
view group, get an instance of the fragment andFragmentManager
, and use theadd()
transaction. - Declare the location for the fragment inside the activity's layout file using the
<FrameLayout>
view group. Then get an instance of the fragment andFragmentManager
, begin a transaction, use theadd()
transaction, and commit the transaction.
Question 3
Which statement gets a reference to a fragment using the fragment's layout resource?
fragment = new SimpleFragment();
SimpleFragment fragment = (SimpleFragment) fragmentManager.findViewById(R.id.fragment_container);
SimpleFragment fragment = (SimpleFragment) fragmentManager.findFragmentById(R.id.fragment_container);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The app displays a second activity when the user taps the Next button.
- The app's second activity includes an Open button. The Open button opens the same fragment (
SimpleFragment
) that appears when the user taps Open in the first activity. - The fragment looks the same, with the X button.
1.2: Communicating with a Fragment
Build and run an app
In the FragmentCommunicate app, when the user makes a choice in the fragment, the app shows the user's choice in a Toast message. The Toast shows "Choice is 0" for "Yes" or "Choice is 1" for "No."
Change the FragmentCommunicate app so that the Toast shows the "Yes" or "No" message rather than "0" or "1."
Answer these questions
Question 1
Which fragment-lifecycle callback draws the fragment's UI for the first time?
onAttach()
onActivityCreated()
onCreate()
onCreateView()
Question 2
How do you send data from an activity to a fragment?
- Set a
Bundle
and use theFragment
.setArguments(Bundle)
method to supply the construction arguments for the fragment. - Use the Fragment method getArguments() to get the arguments.
- Define an interface in the
Fragment
class, and implement the interface in the activity. - Call
addToBackStack()
during a transaction that removes the fragment.
Submit your app for grading
Guidance for graders
Check that the app has the following feature:
- After the user taps Open and makes a choice, the Toast message displays "Choice is Yes" or "Choice is No".
2.1: Building app widgets
Build and run an app
Create an app that has an EditText
view and a button. When the user taps the button, save the string that's displayed in the EditText
view to the shared preferences. Ensure that the app loads this string from the preferences in onCreate()
.
Add a 1x3 app widget that displays the current value of the string. Add a click handler to the entire app widget such that the app opens when the user taps the app widget.
Answer these questions
Question 1
Which of these app-widget components are required ? (Choose all that apply)
- Provider-info file
- Widget-provider class
- Configuration activity
- Layout file
Question 2
Which of these layout and view classes can be used in an app widget?
Button
ConstraintLayout
LinearLayout
ImageButton
CardView
CalendarView
Question 3
In which method in your widget-provider class do you initialize the layout (remote views) for the app widget?
onCreate()
onReceive()
onEnabled()
onUpdate()
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The main activity of the app has an
EditText
view and a button. If you change the string in theEditText
and tap the button, the string is saved. Quitting and restarting the app should load the current string from the shared preferences. - The app widget displays the current text in the app's
EditText
. - Tapping the app widget opens the app.
3.1: Working with sensor data
Build and run an app
Create an app to print the current value of a device's humidity sensor (TYPE_RELATIVE_HUMIDITY
). If the sensor is not available in the device, print "no sensor" instead of the value.
Answer these questions
Question 1
Which of the following features are provided by the SensorManager
class? (Choose all that apply)
- Methods to register and unregister sensor listeners.
- Methods to determine device orientation.
- Constants representing sensor types.
- Constants representing sensor accuracy.
- Methods to indicate whether a sensor is a wake-up sensor.
Question 2
In which Activity
lifecycle method should you register your sensor listeners?
onResume()
onCreate()
onStart()
onRestart()
Question 3
What are best practices for using sensors in your app? (Choose all that apply)
- Register listeners for only for the sensors you're interested in.
- Test to make sure that a sensor is available on the device before you use the sensor.
- Check permissions for the sensor before you use it.
- Register a sensor listener for the slowest possible data rate.
- Don't block
onSensorChanged()
to filter or transform incoming data.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- In
onCreate()
, the app should retrieveSensor.TYPE_RELATIVE_HUMIDITY
from the sensor manager. - In
onStart()
, the app should register a listener for the humidity sensor. InonStop()
, the app should unregister all listeners. - The app should implement
onSensorChanged()
and test that the event's sensor type isTYPE_HUMIDITY
. - When you run the app in the emulator and change the value of the humidity sensor, the app's display should reflect the current value.
3.2: Working with sensor-based orientation
Build and run an app
Create an app based on the TiltSpot app that simulates a bubble level along the long edge of the device. (A bubble or spirit level is a tool that uses colored liquid and an air bubble to show whether a surface is level.) Use a single spot as the "bubble." When the device is level (flat on the table), the bubble should appear in the center of the screen. Move the spot left or right on the screen when one long edge of the device is tilted.
Answer these questions
Question 1
Which sensors report values with respect to Earth's coordinate system, instead of reporting values with respect to the device-coordinate system?
- Geomagnetic field sensor
- Accelerometer
- Gyroscope
- Orientation sensor
Question 2
Which sensors can you use to get the orientation of the device?
- Gyroscope
- Accelerometer and gravity sensor
- Orientation sensor
- Geomagnetic field sensor and accelerometer
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- When you place the device flat on a table, a spot should appear in the middle of the screen.
- When you lift the top or bottom of the device, the spot should move to the upper or lower edge of the screen. The position of the spot should be further away from the center as you tilt the device at a greater angle.
4.0: Optimizing for performance
Build and run an app
Build an app that shows a scrollable list of items for sale, with thumbnail images. When the user taps an image, the app displays a details-view popup with a larger version of the image. You will use this app to complete other performance homework assignments.
- Images must be in WebP format and appropriately sized.
- Supply separate images for thumbnails and detail images.
- To show the product image when the user taps a thumbnail image, you can use a dialog.
Answer these questions
Question 1
Select all of the following that are good basic performance tests you can perform.
- Install your app on the lowest-end device that your target audience might have.
- Observe your friends using the app and make note of their comments.
- Run a small usability test.
- Publish your app and look at the ratings and feedback you receive.
Question 2
Select all that are good ways to approach performance problems.
- Guess at what might be the problem, make a change, and see whether it helps.
- Use a systematic, iterative approach, so that you can measure improvements resulting from your changes to the app.
- Use tools to inspect your app and acquire performance data measurements.
- Run your code and have someone else run your code to evaluate it.
Question 3
Select all of the following that are performance tools available on your mobile device.
- Profile GPU Rendering
- USB debugging
- Show GPU view updates
- Memory Profiler
- Debug GPU Overdraw
- Show CPU usage
Question 4
What is the Performance Improvement Lifecycle technique for improving app performance?
- A systematic approach to testing and improving app performance.
- A process with four phases: gather information , gain insight , take action , and verify .
- A set of tools you can use to measure and improve app performance.
- An iterative approach that allows you to evaluate how changes to your code affect app performance.
Submit your app for grading
App should show a list or grid of items with thumbnail images. When you tap an item, a larger image of the item is displayed.
Guidance for graders
Check that the app has the following features:
- App shows a list of items.
- Tapping an item shows a larger image of the item.
- Images load without delay.
- Scrolling is smooth.
4.1: Analyzing rendering and layout
Build and run an app
In the app you created for the 4.0 homework assignment (4.0: Optimizing for performance), make the following changes:
- Use the same larger images for the thumbnails as for the details view . Run Profile GPU Rendering with the app, take a screenshot of the bars.
- Change the app to use small thumbnail images or text to list the items. Run Profile GPU Rendering with the app again and take a screenshot of the bars.
- Do the two screenshots look different? Comment on the difference or lack of difference.
- Turn on Debug GPU Overdraw. Take a screenshot of your app. If there is a lot of red color, use Layout Inspector to fix your app, then take another screenshot.
Answer these questions
Question 1
How much time does your app have available to calculate and display one frame of content?
- 16 milliseconds
- Less than 16 milliseconds, because the Android framework is doing work at the same time as your app does work.
- It depends on the device.
Question 2
What are some techniques you can use to make rendering faster?
- Reduce overdraw.
- Move work away from the UI thread.
- Use
AsyncTask
. - Use smaller images.
- Compress your data.
- Flatten your view hierarchy.
- Use as few views as possible.
- Use loaders to load data in the background.
- Use efficient views such as
RecyclerView
andConstraintLayout
.
Question 3
Which answer best describes the measure-and-layout stage of the rendering pipeline?
- The GPU measures device dimensions and appropriately sizes views.
- The system traverses the view hierarchy and calculates the size and position of each view inside the view's parent, relative to other views.
- The system optimizes layout times for your views.
Submit your findings for grading
No app to submit for this homework assignment.
Submit the two screenshots you took with Profile GPU Rendering turned on, and the final screenshot you took with Debug GPU Overdraw turned on. Also submit your reflections on why the two screenshots that show Profile GPU Rendering output might be (almost) the same, or why they are different.
Guidance for graders
Check that:
- Student submitted two screenshots of the app with Profile GPU Rendering turned on
- Screenshots are different.
- Student submitted comments explaining the difference.
- If there is no difference, student should reflect on why not.
- If there is a difference, students should reflect on what may have caused it.
- Student submitted one screenshot of the app with Debug GPU Overdraw turned on, and this screenshot shows only a little bit of red coloring.
4.2: Using the Memory Profiler
Build and run an app
- Use the app you created for the 4.0 homework assignment (4.0: Optimizing for performance).
- Run Memory Profiler on the app.
- Take a screenshot of the Memory graph to submit with your observations.
- On the screenshot, identify portions of the graph that are relevant to your app and reflect on them.
- Change your app in a way that noticeably changes the graph. Take a screenshot and submit it with an explanation of the changes.
Answer these questions
Question 1
What tools are available in Android Studio for measuring memory performance?
- Systrace
- Heap dumps
- Debug GPU Overdraw
- Memory Profiler
Question 2
Looking at this Memory Monitor graph, which of the following statements is factually true?
- The app is allocating an increasing amount of memory, and you should investigate for possible memory leaks.
- The app will run out of memory and crash.
- The app will slow down over time because less memory is available.
- More garbage collection events will happen, resulting in a slower app.
Question 3
Select all answers that describe features and benefits of a heap dump?
- A heap dump is a snapshot of the allocated memory at a specific time.
- You can look at a static snapshot of allocated memory.
- You can dump the Java heap to see which objects are using up memory at any given time.
- Heap dumps show how memory is allocated over time.
- Doing several heap dumps over an extended period can help you identify memory leaks.
Question 4
What are the benefits of recording memory allocations? Select up to four.
- You can track allocations and deallocations over time.
- You can track how much space files take up on each partition.
- You can inspect the call stack and find out where in your code an allocation was made.
- You can track down which objects might be responsible for memory leaks.
- You can record memory allocations during normal and extreme user interactions. This recording lets you identify where your code is allocating too many objects in a short time, or allocating objects that leak memory.
Submit your findings for grading
No app to submit for this homework assignment.
Submit the annotated screenshot that you took of the Memory graph, along with your observations.
Guidance for graders
Check that:
- Student submitted annotated screenshot of the app with Memory Profiler turned on
- Student submitted comments relating the graph to their app.
- Student submitted a second, different screenshot, along with explanations on what they did to cause this change, as well as reflections on the change.
4.3: Optimizing network, battery, and image use
Answer these questions
Question 1
On mobile devices, what uses up battery power?
- Mobile radio
- Wi-Fi
- Keeping the Display open
- Running your device in airplane mode
- Any hardware on the device that is actively in use
Question 2
Your app can affect the amount of power that some device components use. Which of the following device components does this include? Select up to three.
- Power and volume buttons
- Display (managing wake lock)
- Mobile radio (batching requests, size of requests)
- GPU (complex visual content, media content)
Question 3
Which of the following are best practices you should always incorporate in your app?
- Defer all network requests until the user's device is on Wi-Fi and plugged in.
- Use the most efficient image format for the type of images your app uses.
- Compress all your data.
- Respond to user actions immediately.
- Always prefetch as much data as possible.
- If you must poll the server, use an exponential back-off pattern.
- To make your app work offline, cache data locally.
Question 4
What are best practices for working with images?
- Use the smallest image possible. Resize images used for thumbnails.
- Don't use images. They take up too much space.
- Always use a quality setting that does not diminish the user experience but results in a smaller image.
- If you store images on a remote server, make multiple sizes available for each image. That way, your app can request the appropriate size for the device it's running on.
- WebP, PNG, and JPG image formats can be used interchangeably.
- If possible, use the WebP image format, because it usually results in smaller, higher-quality images.
Submit your findings for grading
No app to submit for this homework assignment.
5.1: Using resources for languages
Build and run an app
In the LocaleText1 app, make the following changes:
- Add Spanish for Mexico and Arabic for any region.
- Add translations for both languages.
- Test the app with both language choices.
Answer these questions
Question 1
Which of the following attributes should you add to the android:layout_marginLeft
attribute to support an RTL language?
android:layout_marginEnd
android:layout_marginStart
app:layout_constraintLeft_toRightOf
app:layout_constraintStart_toEndOf
Question 2
Which of the following attributes should you add to the app:layout_constraintLeft_toRightOf
attribute to support an RTL language?
app:layout_constraintRight_toLeftOf
app:layout_constraintStart_toEndOf
app:layout_constraintRight_toRightOf
app:layout_constraintEnd_toEndOf
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- If the user chooses Español (Mexico), the app displays Spanish.
- If the user chooses Arabic and any country, the app displays Arabic in an RTL layout.
5.2: Using the locale
Build and run an app
The LocaleText3 app calculates and shows a total after the user enters a quantity and taps the Done button. Modify the LocaleText3 app as follows:
- Modify the
onEditorAction()
method of theOnEditorActionListener
anonymous inner class. Add code that calculates the total from the quantity and price, then shows the total. - The code you add should make the calculation price times quantity .
- If the user chooses Français (France), the code should show the total in euros. If the user chooses Hebrew (Israel), the code should show the total in new shekels. Otherwise, the code should show the total in U.S. dollars.
- This code is similar to the code you added in the practical to show the price in euros or new shekels.
Answer these questions
Question 1
Which of the following statements returns a general-purpose number format for the user-selected language and locale?
NumberFormat numberFormat = NumberFormat.getInstance();
String myFormattedQuantity = numberFormat.format(myInputQuantity);
String deviceLocale = Locale.getDefault().getCountry();
Question 2
Which of the following statements converts a locale-formatted input quantity string to a number?
NumberFormat numberFormat = NumberFormat.getInstance();
String myFormattedQuantity = numberFormat.format(myInputQuantity);
myInputQuantity = numberFormat.parse(v.getText().toString()).intValue();
Question 3
Which of the following statements retrieves the country code for the user-chosen locale?
String deviceLocale = Locale.getDefault().getCountry();
String deviceLocale = Locale.getDisplayCountry();
String deviceLocale = Locale.getDisplayName();
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- If the user chooses Français (France), the app displays the total in euros.
- If the user chooses Hebrew (Israel), the app displays the total in new shekels.
- If the user chooses any other locale, the app displays the total in U.S. dollars.
6.1: Exploring accessibility in Android
Answer these questions
Question 1
Why should you consider making your app accessible?
- Accessibility enables your app to be used by people with disabilities.
- Accessibility allows your users—those users with disabilities and those users without—to customize their experiences of your app.
- Accessible apps run faster.
- Testing your app with accessibility in mind can reveal user-experience issues or limitations you might not have recognized.
Question 2
Which of the following are accessibility features available in Android?
- TalkBack
- Switch Access
- Text-to-speech
- Closed captions
- Magnification
- Ability to change display or font size
Question 3
What is TalkBack?
- An app that converts audio into readable captions on the screen.
- An app that enables screen content to be presented on a refreshable braille display.
- An app that reads screen content aloud.
- An app that magnifies the computer screen.
Question 4
How should you test your app for accessibility?
- Turn on TalkBack and manually try to use your app.
- Add unit tests and Espresso tests.
- Use tools such as Accessibility Scanner and Android Studio's lint tool to reveal potential accessibility problems.
- Use the Android Testing Support Library to enable automated accessibility testing.
Submit your findings for grading
No app to submit for this homework assignment.
6.2: Creating accessible apps
Build and run an app
In the SimpleAccessibility app, add three new images:
- Add a description for the first image that describes the image. Ensure that the image is focusable.
- Add a decorative image with no description. Ensure that the image is not focusable.
- For the third image, add a text label that describes the image.
Answer these questions
Question 1
Which of the following attributes should you add to ImageView
and ImageButton
elements to enable screen readers to describe the image?
android:text
android:contentDescription
android:hint
android:labelFor
Question 2
When should you add a content description to an ImageView
or ImageButton
?
- When the image's role on the screen is solely decorative and does not provide any function or meaning.
- When an image's dimensions are very small and the image is difficult to see.
- When the image is meaningful to the user in their use of the app.
- When the image is also a button.
Question 3
When do you NOT need to add a content description to a view element?
- When the view is a
TextView
orEditText
. - When the view is an
ImageView
that serves only a decorative purpose. - When the view is a checkbox or radio button.
- When the view has an associated text view that includes with the
android:labelFor
attribute. - All of the above.
Submit your findings for grading
Guidance for graders
Check that the app has the following features:
- The app should have three new images, of any kind. The third image should have a text view that serves as a label.
- The layout for the first new image should include the following:
- An
android:contentDescription
attribute with a description of the image. - An
android:focusable="true"
attribute. - The layout for the second new image should include the following:
- An
android:contentDescription
attribute with a null string (""
). - An
android:focusable="false"
attribute. - The layout for the third new image should include the following:
- An
android:focusable="true"
attribute. - A
TextView
element with theandroid:labelFor
attribute. Theandroid:labelFor
attribute should indicate the ID of the image.
7.1: Using the device location
Build and run an app
In the WalkMyAndroid app, add a second TextView
to the app that shows the following:
- Accuracy in meters.
- Speed in meters per second.
Hint: See the getSpeed
()
and getAccuracy
()
documentation.
Answer these questions
Question 1
Which API do you use to request the last known location on the device?
getLastKnownLocation()
method in theFusedLocationProviderApi
classgetLastKnownLocation()
method in theLocationServices
classgetLastLocation()
method in theFusedLocationProviderClient
classgetLastLocation()
method in theLocationServices
class
Question 2
Which class do you use for handling geocoding and reverse geocoding?
GeoDecoder
Geocoder
ReverseGeocoder
GeocoderDecoder
Question 3
Which method do you use for periodic location updates ?
requestPerodicUpdates()
method in theFusedLocationClient
classrequestLocationUpdates()
method in theFusedLocationProviderClient
classrequestUpdates()
method in theFusedLocationProviderClient
classrequestLocationUpdates()
method in theFusedLocationProvider
class
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The app displays a second
TextView
, in addition to theTextView
that shows the address. - The second
TextView
shows speed and accuracy.
8.1 Using the Places API
Build and run an app
Modify the WalkMyAndroidPlaces app to display a new Android image for shopping malls:
- Create a new Android image for shopping malls. (Hint: Use the Androdify tool.)
- If the place type is
TYPE_SHOPPING_MALL
, replace the Android image with your image. - To test your app, pick a shopping mall from the
PlacePicker
dialog. Make sure that your new Android image is animated, and thatTextView
object is updated with the shopping mall's name and address.
Answer these questions
Question 1
Which class displays a dialog that allows a user to pick a place using an interactive map ?
PlaceDetectionApi
GeoDataApi
PlacePicker
PlaceAutocomplete
Question 2
What are the two ways to add the autocomplete widget to your app?
- Embed a PlaceAutocompleteFragment fragment.
- Autocomplete is added along with the
PlacePicker
widget. - Use an intent to launch the autocomplete activity.
- Add a
PlaceAutocompleteActivity
object to your app.
Question 3
If your app uses the PlacePicker
UI or the PlaceDetectionApi
interface, what permission does your app require?
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
andACCESS_COARSE_LOCATION
ACCESS_LOCATION_EXTRA_COMMANDS
ACCESS_FINE_LOCATION
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- When you tap the Pick a Place button, the place picker UI opens.
- When you pick a shopping mall on the map, the new Android image is displayed.
- The image is animated.
- The
TextView
updates to show the name and address of the shopping mall.
9.1 Adding a Google Map to your app
Build and run an app
- Create a new app that uses the Google Maps Activity template, which loads Google Maps when the app launches.
- When the Google Map is loaded, move the camera to your school location, your home location, or some other location that has meaning for you.
- Add two markers to the map, one at your school location and one at your home or some other meaningful location.
- Customize the marker icons by changing the default color or replacing the default marker icon with a custom image.
Hint: See the onMapReady (GoogleMap googleMap)
documentation.
Answer these questions
Question 1
Which method is called when the map is loaded and ready to be used in the app ?
onMapReady (
GoogleMap
googleMap)
onMapLoaded (
GoogleMap
googleMap)
onMapCreate (
GoogleMap
googleMap)
onMapInitialize (
GoogleMap
googleMap)
Question 2
Which Android components can you use to include Google Maps in your app ?
MapView
andMapFragment
MapFragment
andMapActivity
MapView
andMapActivity
- Only
MapFragment
Question 3
What types of maps does the Google Maps Android API offer?
- Normal, hybrid, terrain, satellite, and roadmap
- Normal, hybrid, terrain, satellite, and "none"
- Hybrid, terrain, satellite, roadmap, and "none"
- Normal, terrain, satellite, imagemap, and "none"
Question 4
What interface do you implement to add on-click functionality to a point of interest (POI)?
GoogleMap.OnPoiListener
GoogleMap.OnPoiClickListener
GoogleMap.OnPoiClick
GoogleMap.OnPoiClicked
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- When the app is launched, the Google Map is displayed correctly, indicating that an API key was generated properly.
- After the Google Map loads, the camera moves to the student's home or school location. In the code, this step should happen in the
onMapReady (GoogleMap googleMap)
callback method. - Markers are displayed at the student's school location and another location, such as the student's home.
- The two markers are customized. For example, the markers use a color other than the default red color, or they use a custom icon.
10.1: Creating a custom view
Build and run an app
In the CustomEditText app, add a custom view that enables phone-number entry:
- In the layout, add a second version of the
EditTextWithClear
custom view underneath the first version (the Last name field). - Use XML attributes to define the second version of the custom view as a phone number field that accepts only numeric phone numbers as input.
Answer these questions
Question 1
Which constructor do you need to inflate the layout for a custom view? Choose one:
public MyCustomView(Context context)
public MyCustomView(Context context, AttributeSet attrs)
public static SimpleView newInstance() { return new SimpleView(); }
protected void onDraw(Canvas canvas) { super.onDraw(canvas) }
Question 2
To define how your custom view fits into an overall layout, which method do you override?
onMeasure()
onSizeChanged()
invalidate()
onDraw()
Question 3
To calculate the positions, dimensions, and any other values when the custom view is first assigned a size, which method do you override?
onMeasure()
onSizeChanged()
invalidate()
onDraw()
Question 4
To indicate that you'd like your view to be redrawn with onDraw()
, which method do you call from the UI thread, after an attribute value has changed?
onMeasure()
onSizeChanged()
invalidate()
getVisibility()
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The app displays a Phone number field with a clear (X) button on the right side of the field, just like the Last name field.
- The second version of the
EditTextWithClear
custom field (Phone number) should use theandroid:inputType
attribute so users can enter values with a numeric keypad.
11.1: Applying clipping to a Canvas object
Build and run an app
Create a MemoryGame app that hides and reveals "cards" as the user taps on the screen. Use clipping to implement the hide/reveal effect.
- You can use simple colored squares or shapes for the "cards."
- If the user reveals two matching cards, show a congratulatory toast. If the user reveals two cards that don't match, show an encouraging message telling them to tap to continue.
- Click handling: On the first tap, show the first card. On the second tap, show the second card and display a message. On the next tap, restart.
Answer these questions
Question 1
To display something to the screen, which one of the following draw and animation classes is always required?
View
Drawable
Canvas
Bitmap
Question 2
What are some properties of drawables?
- Drawables are drawn into a view and the system handles drawing.
- Drawables are best for simple graphics that do not change dynamically.
- Drawables offer the best performance for game animations.
- You can use drawables for frame-by-frame animations.
Question 3
Which of the following statements are true?
- You use a Canvas object when elements in your app are redrawn regularly.
- To draw on a
Canvas
, you must override theonDraw()
method of a custom view. - Every view has a
Canvas
that you can access. - A
Paint
object holds style and color information about how to draw geometries, text, and bitmaps.
Question 4
What is clipping?
- A technique for defining regions on a
Canvas
that will not be drawn to the screen. - A technique for making the
Canvas
smaller so theCanvas
uses less memory. - A way of telling the system which portions of a
Canvas
do not need to be redrawn. - A technique to consider when you're trying to speed up drawing.
- A way to create interesting graphical effects.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- When the user taps, the app reveals a "card."
- When the user taps again, the app reveals a second "card" and shows a toast congratulating or encouraging the user.
- On the third tap, the game restarts.
- The code uses a
Canvas
object and clipping methods to achieve the hide/reveal effects of playing the game.
11.2: Creating a SurfaceView object
Build and run an app
Implement the same MemoryGame app that you created in the 11.1 homework, but use a SurfaceView
object.
The MemoryGame app hides and reveals "cards" as the user taps on the screen. Use clipping to implement the hide/reveal effect.
- You can use simple colored squares or shapes for the "cards."
- If the user reveals two matching cards, show a congratulatory toast. If the user reveals two cards that don't match, show an encouraging message telling them to tap to continue.
- Click handling: On the first tap, show the first card. On the second tap, show the second card and display a message. On the next tap, restart.
Answer these questions
Question 1
What is a SurfaceView
?
- A view in your app's view hierarchy that has its own separate surface.
- A view that directly accesses a lower-level drawing surface.
- A view that is not part of the view hierarchy.
- A view that can be drawn to from a separate thread.
Question 2
What is the most distinguishing benefit of using a SurfaceView
?
- A
SurfaceView
can make an app more responsive to user input. - You can move drawing operations away from the UI thread.
- Your animations may run more smoothly.
Question 3
When should you consider using a SurfaceView
? Select up to three.
- When your app does a lot of drawing, or does complex drawing.
- When your app combines complex graphics with user interaction.
- When your app uses a lot of images as backgrounds.
- When your app stutters, and moving drawing off the UI thread could improve performance.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- When the user taps, the app reveals a "card."
- When the user taps again, the app reveals a second "card" and shows a toast congratulating or encouraging the user.
- On the third tap, the game restarts.
- The code uses a
SurfaceView
object, and a separate thread for drawing.
12.1: Creating animations
Build and run an app
Create an app that uses non-trivial property animation. For example, animate multiple properties, animate multiple objects, or create complex animations by using animator sets. Below are some ideas.
- Create an animation where text spins and recedes while getting smaller. Or text appears from nowhere and spins to fill the screen. Combine these two animations.
- Create an animation that simulates a ball that grows until it bursts into multiple smaller balls.
- Create a simple card game, where touching a card flips the card around.
Answer these questions
Question 1
What types of animations are available with Android?
- View animation
- Property animation
- Canvas animation
- Drawable animation
- Physics-based animation
Question 2
Which of the following statements about property animation are true?
- Property animation lets you define an animation to change any object property over time.
- Property animation lets you create objects with custom properties that you can animate.
- A property animation tracks time and adapts its velocity to the time.
- Property animation lets you animate multiple properties with animator sets.
- The duration of a property animation is fixed.
Question 3
What are the advantages of using physics-based animation libraries? Select up to three answers.
- Physics-based animations are more realistic than other types of animations, because physics-based animations appear more natural.
- It is easier to use the physics-based support library than to implement adaptive animations yourself.
- Physics-based animations keep momentum when their target changes and end with a smoother motion than other types of animations.
- Physics-based animations are easier to combine with audio.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- App uses property animation to implement a non-trivial animation, animates multiple objects, and/or uses animator sets.
13.1: Simple media playback
Build and run an app
Use the SimpleVideoView app as a starting point for an app that plays multiple videos.
- The main activity for the app contains a list of videos. Use a
RecyclerView
for the list. - Clicking a single item in the list starts the video playback activity containing the
VideoView
andMediaController
. - At the end of the video playback, automatically start playing the next video in the list.
- At the end of the last video in the list, finish the activity and return to the list of videos.
Answer these questions
Question 1
VideoView
is a wrapper for which two classes?
Video
andView
MediaPlayer
andMediaController
MediaPlayer
andSurfaceView
MediaPlayer
andUri
Question 2
Which of the following sources can VideoView
play?
- The URL of a video sample located on a web server
- A sample contained on external device media
- A YouTube video URL
- A sample embedded in the app's resources
Question 3
Which of these callbacks are available for media events in the VideoView
class?
onError()
onInfo()
onPrepared()
onBufferingUpdate()
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The app's main activity contains a list of video samples to play, in a
RecyclerView
. The videos may come from any source. - Clicking any video starts a new activity with a
VideoView
and a media controller. - Skip to the end of the video playback. The next video in the list should play.
- At the end of the playback of the last video, close the activity and return to the list of videos.
- The code should use the
onComplete()
callback to determine whether to play the next video in the list or finish playing altogether.
14.1: Working with Architecture Components: Room, LiveData, ViewModel
Build and run an app
Create an app that uses a Room database, ViewModel
, and LiveData
to display the data when the data changes. You can make this as simple or as sophisticated as you wish, as long as the app uses all the required components, and the data updates on the screen when the data changes in the database.
Here are some hints and ideas:
- Create a simple app that stores one text document whose contents are displayed in a
TextView
. When the user edits the document, changes appear in theTextView
. - Create a question-answer app. Start out with only questions and let users add new questions and answers.
- As a challenge, add a button to each answer in the question-answer app that displays additional information that's stored in a different repository. The information could come from a file on the device, or a page on the internet.
Answer these questions
Question 1
What are the advantages of using a Room database?
- Creates and manages an Android SQLite database for you.
- Eliminates a lot of boilerplate code.
- Helps you manage multiple backends.
- Using a DAO, provides a mechanism for mapping Java methods to database queries.
Question 2
Which of the following are reasons for using a ViewModel
?
- Cleanly separates the UI from the backend.
- Often used with
LiveData
for changeable data that the UI will use or display. - Prevents your data from being lost when the app crashes.
- Acts as a communication center between the Repository and the UI.
ViewModel
instances survive device configuration changes.
Question 3
What is the DAO?
- Short for "data access object."
- A library for managing database queries.
- An annotated interface that maps Java methods to SQLite queries.
- A class whose methods run always in the background, not on the main thread.
- A class that the compiler checks for SQL errors, then uses to generate queries from the annotations.
Question 4
What are features of LiveData
?
- Updates automatically when used with Room if all the intermediate levels also return
LiveData
(DAO,ViewModel
, Repository). - Uses the observer pattern and notifies its observers when its data has changed.
- Automatically updates the UI when it changes.
- Is lifecycle aware.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- Uses the Room database to store data.
- Uses
ViewModel
andLiveData
to manage and display changing data. - Has a way to edit data and show changes.
14.2: Working with Architecture Components: Deleting and updating data
Build and run an app
You have learned about many ways to store data. Choosing the right storage option depends on how large your data is, and how long the data has to survive.
Create an app that demonstrates how data stored in at least two different locations survives configuration changes and the destruction of the app. You can do this by storing small pieces of data, such as strings, in different data stores.
- The app should demonstrate what happens to data that is not saved.
- The app could demonstrate what happens to data that is preserved with
saveInstanceState
, data that usesLiveData
with aViewModel
, and data that is stored in a file or database.
Answer these questions
Question 1
Android Architecture Components provide some convenience annotations for DAOs. Which of the following are available.
@Dao
@Insert
@Delete
@Update
@Query
@Select
Question 2
What are the benefits of using Architecture Components?
- Architecture Components help you structure your app in a way that is robust and testable.
- Architecture Components help you create better UIs.
- Architecture Components provide a simple, flexible, and practical approach to structuring your app.
- If you use the the provided libraries and architecture, your app is more maintainable with less boilerplate code.
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- Saves data in at least two different ways.
- Demonstrates how data is preserved differently with different storage options.