Appendix

Answers to Exercises

This appendix includes the answers to the end-of-chapter exercises.

Chapter 1 ANSWERS

  1. An AVD is an Android Virtual Device. It represents an Android emulator, which emulates a particular configuration of an actual Android device.
  2. Because Jelly Bean had the largest install base at the time.
  3. Software Development Kit.

Chapter 2 ANSWERS

  1. The company domain is used to name the Java package to which your code will belong.
  2. This screen adds commonly used features to your project at the time the project is created.
  3. Code completion is an invaluable tool that shows you contextual options for completing the piece of code that you are trying to write.
  4. Breakpoints are mechanisms that enable Android Studio to temporarily pause execution of your code to let you examine the condition of your application.

Chapter 3 ANSWERS

  1. Activity
  2. android:theme
  3. onCreateDialog()
  4. Intents
  5. startActivityForResult()

Chapter 4 ANSWERS

  1. The dp unit is density independent and 1dp is equivalent to one pixel on a 160-dpi screen. The px unit corresponds to an actual pixel on screen. You should always use the dp unit because it enables your activity to scale properly when run on devices of varying screen size.
  2. With the advent of devices with different screen sizes, using AbsoluteLayout makes it difficult for your application to have a consistent look and feel across devices.
  3. The onPause() event is fired whenever an activity is killed or sent to the background. The onSaveInstanceState() event is similar to the onPause() event, except that it is not always called, such as when the user presses the Back button to kill the activity.
  4. The three events are onPause(), onSaveInstanceState(), and onRetainNonConfigurationInstance().
    • You generally use the onPause() method to preserve the activity's state because the method is always called when the activity is about to be destroyed.
    • For screen orientation changes, however, it is easier to use the onSaveInstanceState() method to save the state of the activity (such as the data entered by the user) using a Bundle object.
    • The onRetainNonConfigurationInstance() method is useful for momentarily saving data (such as images or files downloaded from a web service) that might be too large to fit into a Bundle object.
  5. Adding action items to the Action Bar is similar to creating menu items for an options menu — simply handle the onCreateOptionsMenu() and onOptionsItemSelected() events.

Chapter 5 ANSWERS

  1. You should inspect the isChecked() method of each RadioButton to determine whether it has been selected.
  2. You can use the getResources() method.
  3. The code snippet to obtain the current date is as follows:
            //—-get the current date—-
            Calendar today = Calendar.getInstance();
            yr = today.get(Calendar.YEAR);
            month = today.get(Calendar.MONTH);
            day = today.get(Calendar.DAY_OF_MONTH);
            showDialog(DATE_DIALOG_ID);
  4. The three specialized fragments are ListFragment, DialogFragment, and PreferenceFragment.
    • The ListFragment is useful for displaying a list of items, such as an RSS listing of news items.
    • The DialogFragment allows you to display a dialog window modally and is useful when you want a response from the user before allowing him to continue with your application.
    • The PreferenceFragment displays a window containing your application's preferences and allows the user to edit them directly in your application.

Chapter 6 ANSWERS

  1. The ImageSwitcher enables images to be displayed with animation. You can animate the image when it is being displayed, as well as when it is being replaced by another image.
  2. The two methods are onCreateOptionsMenu() and onOptionsItemSelected().
  3. The two methods are onCreateContextMenu() and onContextItemSelected().
  4. To prevent launching the device's web browser, you need to implement the WebViewClient class and override the shouldOverrideUrlLoading() method.

Chapter 7 ANSWERS

  1. You can use the PreferenceActivity class.
  2. The method name is getExternalStorageDirectory().
  3. The permission is WRITE_EXTERNAL_STORAGE.

Chapter 8 ANSWERS

  1. The code is as follows:
            Cursor c;
            if (android.os.Build.VERSION.SDK_INT <11) {
                //---before Honeycomb---
                c = managedQuery(allContacts, projection,
                        ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                        new String[] {"%jack"},
                        ContactsContract.Contacts.DISPLAY_NAME + " ASC");
            } else {
                //---Honeycomb and later---
                CursorLoader cursorLoader = new CursorLoader(
                        this,
                        allContacts,
                        projection,
                        ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                        new String[] {"%jack"},
                        ContactsContract.Contacts.DISPLAY_NAME + " ASC");
                c = cursorLoader.loadInBackground();
            }
  2. The methods are getType(), onCreate(), query(), insert(), delete(), and update().
  3. The code is as follows:
            <provider android:name="BooksProvider"
                    android:authorities="net.learn2develop.provider.Books"/>

Chapter 9 ANSWERS

  1. You can either programmatically send an SMS message from within your Android application or invoke the built-in Messaging application to send it on your application's behalf.
  2. The two permissions are SEND_SMS and RECEIVE_SMS.
  3. onUpgrade()

Chapter 10 ANSWERS

  1. The likely reasons are as follows:
    • No Internet connection
    • Incorrect placement of the <uses-library> element in the AndroidManifest.xml file
    • Missing INTERNET permission in the AndroidManifest.xml file
  2. Geocoding is the act of converting an address into its coordinates (latitude and longitude). Reverse geocoding converts a pair of location coordinates into an address.
  3. The two providers are as follows:
    • LocationManager.GPS_PROVIDER
    • LocationManager.NETWORK_PROVIDER
  4. The method is addProximityAlert().

Chapter 11 ANSWERS

  1. The permission is INTERNET.
  2. The classes are JSONArray and JSONObject.
  3. The class is AsyncTask.

Chapter 12 ANSWERS

  1. A separate thread should be used because a service runs on the same process as the calling activity. If a service is long-running, you need to run it on a separate thread so that it does not block the activity.
  2. The IntentService class is similar to the Service class except that it runs the tasks in a separate thread and automatically stops the service when the task has finished execution.
  3. The three methods are doInBackground(), onProgressUpdate(), and onPostExecute().
  4. The service can broadcast an intent, and the activity can register an intent using an IntentFilter class.
  5. The recommended method is to create a class that uses AsyncTask. This ensures that the UI is updated in a thread-safe manner.