Homework Assignments: Lesson 9 & 10 & 11
Contents:
- 9.1: Shared Preferences
- 9.2: App Setting
- 10.1: SQLite Database
- 11.1: Content Providers
- 11.2: Loaders
9.1: Shared Preferences
Build and run an app
Open the ScoreKeeper app that you created in the Drawables, Styles, and Themes lesson.
- Replace the saved instance state with shared preferences for each of the scores.
- Test the app:
- Rotate the device to ensure that configuration changes read the saved preferences and update the user interface.
- Stop the app and restart it to ensure that the preferences are saved.
- Add a Reset button that resets the score values to 0 and clears the shared preferences.
Answer these questions
Question 1
In which lifecycle method do you save the app state to shared preferences?
Question 2
In which lifecycle method do you restore the app state?
Question 3
Can you think of a case where it makes sense to have both shared preferences and instance state?
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The app retains the scores on rotation.
- The app retains the current scores after being stopped and restarted.
- The app saves the current scores to the shared preferences in the
onPause()
method. - The app restores shared preferences in the
onCreate()
method. - The app displays a Reset button that resets the scores to 0.
- The implementation of the on click handler method for the reset button:
- Resets both score variables to 0.
- Updates both text views
- Clears the shared preferences.
9.2: App Settings
Build and run an app
Open the DroidCafeWithSettings app that you created in the Adding Settings to an App lesson.
- Add a ListPreference (a dialog with radio buttons) to the "General" group of settings. Put it in the "General settings" screen layout, below the "Add friends to order messages" ListPreference.
- Edit the string arrays used for the ListPreference to include the ListPreference title "Choose a delivery method." Use the same delivery choices that are used in the radio buttons in the OrderActivity.
- Make the user's chosen Delivery setting appear in the same toast message as the chosen Market and Recommendations settings.
- Extra credit: Show the selected delivery method as the setting summary text that appears underneath the ListPreference title. Enable this text to change with each update.
Answer these questions
Question 1
In which file do you define the array of entries and the array of values for the ListPreference? Choose one:
- pref_general.xml
- strings.xml
- menu_main.xml
- content_main.xml
Question 2
In which file do you use the array of entries and the array of values in setting up the ListPreference, and also set the ListPreference key and default value? Choose one:
- pref_general.xml
- strings.xml
- menu_main.xml
- SettingsActivity.java
Question 3
How do you set the default values for settings the first time an activity runs?
- Assign the default value using the
android:defaultValue
attribute for each setting preference in the preferences XML file. - Set the default value in the
onCreate()
method for the activity usingPreferenceManager.setDefaultValues()
. - Both of the above.
Question 4
For an app that supports Android 3.0 and newer versions, the best practice for settings is to use a Settings Activity that extends Activity, and a fragment for each preference XML file that extends PreferenceFragment. But how do you remain compatible with the v7 appcompat library when extending an Activity with AppCompatActivity?
Question 5
When using the SharedPreferences interface for accessing and modifying preference data such as settings, the following statement reads the setting preference defined by the delivery
key:
String deliveryPref = sharedPref.getString("delivery", "1");
- True or false? The "1" string argument is the value to return if the setting preference does not exist. It is usually a string for the default value of the setting, which for this example is "1".
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- The
onCreate()
method reads thedeliveryPref
setting usingsharedPref.getString()
. - The pref_general.xml file includes a ListPreference that uses for its entries an array of delivery choices.
- Extra credit: The statement
bindPreferenceSummaryToValue(findPreference("delivery"))
has been added to theonCreate()
method of the GeneralPreferenceFragment class in the SettingsActivity in order to show the delivery choice in the preference summary.
10.1: SQLite Database
README: In the next group of homework assignments (10.1, 11.1, 11.2), you build 2 apps. They relate to each other in the same way as the apps you built in the corresponding practicals, as follows:
- The first app, in 10.1, is a TODO list that uses a SQLite database to store items. The app also includes a way to add, display, and edit items.
- In 11.1, you extend the TODO list app to use a content provider to serve data from the SQLite database to the user interface.
- In 11.2, you build an app called ShowToDoItems that accesses the TODO list's content provider and loads to-do items using a loader.
Build and run an app that uses a SQLite database
Create an app called TODO with a SQLite database where the user can create and edit to-do list items that are stored in the database.
- Extend the SQLiteOpenHelper class with
query()
,insert()
, andupdate()
methods implemented. - Include the app features described below.
Features:
- The user can add new items to the list.
- Each item in the database includes a task to do, creation and completion dates, and whether or not the task has been completed.
- When the app starts, the screen shows a list of incomplete to-do items sorted by creation date.
- The UI includes an Options menu item to start an activity that shows the completed tasks.
- The user can change an item's completion status. When the user marks a task as completed, it is marked complete and the creation date is replaced with the completion date.
- When the user taps an incomplete item, edit mode is triggered, and the user can edit the item.
- When the app is restarted, the latest state of items is visible, which demonstrates that the data was saved and reloaded.
Tips:
- One way to implement the UI is to use a RecyclerView that starts an edit activity when an item is clicked.
- You will not be graded on the way in which you implement the UI, or how the UI looks, as long as the UI demonstrates the functionality.
- Apps that use RecyclerView and the SQLite database follow a pattern. Examine and reuse code that you wrote for the SQLite Database lesson and the Searching a SQLite Database lesson.
- Make sure you cleanly separate data from the user interface. You will extend this to-do app to complete future homework assignments about content providers and loaders.
Answer these questions
Question 1
How much code were you able to reuse from other apps? How much time do you think that saved you? How much did using another app as an example help you structure your app? There are no right or wrong answers.
Question 2
What are some of the benefits of using a SQLiteOpenHelper class? Check all that apply.
- Provides utilities to simplify the tasks of creating and initializing the database.
- Provides the
onUpgrade()
method. Most importantly, if the upgrade fails, it does the rollback for you. - Using a recommended pattern makes it easier to understand, maintain, and extend the app.
Question 3
Which of the following are benefits of using a SQLite database to store your data? Check all that apply.
- Uses SQL queries to retrieve data, allowing you to match given constraints and conditions.
- Data is stored persistently and securely, and can be retrieved efficiently.
- Other apps can use your data.
Submit your app for grading
Guidance for graders
There are no right or wrong answers to Question 1. It's important that students reflect and realize the benefits of building on their own and others' work.
The UI that the student chooses isn't a factor for grading, as long as the app demonstrates database functionality. Students have a lot of freedom in how to implement this functionality.
Check that the app has the following features:
- Includes a SQLiteOpenHelper class with
query()
,insert()
, andupdate()
methods implemented to support the required functionality. - When the apps starts, the screen shows a list of to-do items sorted by creation date.
- When the user interacts with an item, edit mode is triggered, and the user can edit the item.
- The user can change an item's completion status.
- Includes an Options menu item that lets the user see completed items.
- When an item is changed, the UI reflects the change.
- When the app is restarted, the latest state of the items is visible, which demonstrates that the data was saved and reloaded.
11.1: Content Providers
Extend the TODO list app from homework 10.1 to use a content provider.
- Add a Contract class for the common and public constants, URIs, and the database schema.
- Add a ContentProvider class that handles URIs and implements
query()
,insert()
, andupdate()
methods. - Add the content provider to the AndroidManifest.xml file.
Features:
- From the user's perspective, the app should have exactly the same functionality as the TODO app that you built for the 10.1 homework assignment.
- All queries go through the content provider, and from there to the SQLite database.
Tips:
- If you need help, see the word_list_sql_with_content_provider app from the Sharing Content with Other Apps lesson.
Answer these questions
Question 1
What are the primary purposes of a content provider?
- Separate data from the user interface.
- Make data available to other apps.
- Separate the back end from the user interface.
Question 2
What are some of the benefits of using a Contract class?
- Contract can be public so other apps can find out how to access a content provider.
- You only need to define common constants once.
- It defines parts of an app that cannot be changed.
- For larger and more complex apps, it collects constants into one place for easier maintenance.
Question 3
Why does the content provider need to be declared in the Android Manifest?
- To tell the Android Framework what the unique ID of the content provider is.
- To make sure there is only one content provider for each app.
- To tell the Android Framework the properties, such as permissions for this content provider.
Submit your app for grading
Guidance for graders
The UI that the student chooses is not a factor for grading, as long as it demonstrates app functionality.
Check that the app implements the following:
- Uses the Contract class for the URIs and other constants.
- Includes a ContentProvider class that handles URIs and implements
query()
,insert()
, andupdate()
methods that interact with the database. - App is architected so that activities use the content provider's query(), insert(), and update() methods to interact with the database.
- When the app is restarted, the latest state of the items is visible, which demonstrates that the data was saved and reloaded.
11.2: Loaders
Build and run an app called ShowToDoItems that uses a loader to fetch and display data from the content provider that you used in the TODO app from homework 11.1.
- Create a basic UI to display incomplete TODO list items.
- Implement a Contract class for constants for the TODO app's content provider.
- Implement
LoaderManager.LoaderCallbacks<>
to load data from the content provider. - Add a loader manager to manage your loader.
Features:
- When the apps starts, the screen shows a list of to-do items fetched from the running content provider of the TODO app.
- When the data in the TODO app's database changes, it also updates in the ShowToDoItems app.
Tips:
- Re-use UI elements from previous apps.
- Don't forget to add permissions to the manifest file.
- If you need help, see the WordListClient and WordListLoader apps on GitHub.
Answer these questions
Question 1
Which of the following are benefits of using loaders?
- Loaders are fast.
- Loaders run on separate threads to prevent janky or unresponsive UI.
- Loaders simplify thread management by providing callback methods when events occur.
- Loaders persist and cache results across configuration changes to prevent duplicate queries.
- Loaders can implement an observer to monitor for changes in the underlying data source.
Question 2
In building the ShowToDoItems app, why don't you have to implement a content observer?
- The loader manager handles data observation for you.
- CursorLoader automatically registers a ContentObserver to trigger a reload when data changes.
- The TODO list app sends new data to the ShowToDoItems app if the items in the database change.
Submit your app for grading
Guidance for graders
The UI that the student chooses is not a factor for grading, as long as it demonstrates app functionality.
Check that the app has the following features:
- Uses the Contract class.
- Implements
LoaderManager.LoaderCallbacks<>
and uses a loader manager. - When the apps starts, the screen shows a list of to-do items fetched from the running content provider of the TODO app.
- When the data in the TODO app's database changes, it also updates in the ShowToDoItems app.