Chris Rider and Eric Rolf - Introduction to Android

Embed Size (px)

Citation preview

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    1/160

    Introduction toAndroidMarch 5, 2012

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    2/160

    Introductions

    Speaker:

    Chris Rider

    Northern Kentucky University

    Center for Applied Informatics

    Senior Technology Architect

    [email protected]

    859-572-1302

    Assistants: Spencer Egart

    mailto:[email protected]:[email protected]
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    3/160

    Resources

    http://developer.android.com

    Sams Teach Yourself Android Application Development in 24

    hours; Lauren Darcey, Shane Conder

    Apress Beginning Android; Mark L. Murphy

    http://developer.android.com/http://developer.android.com/
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    4/160

    Prerequisites for Android

    Development Knowledge of the Java programming language is highly

    recommended. If not, previous experience in another Object

    Oriented Programming (OOP) language will be helpful

    Understanding of OOP concepts. Java is an OOP language and

    Android takes full advantage of this. Previous experience with an Integrated Development

    Environment (IDE) is helpful, but not required

    Windows, Mac, or Linux computer

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    5/160

    Introduction

    Android is quickly becoming one of the dominate mobile

    platforms.

    Android is used in mobile phones, cars, BluRay players,

    tablets, and many other consumer electronic devices

    Open Handset Alliance formed in 2007 (Google is theprominent member)

    In 2008, the Android platform was announced

    T-Mobile shipped the G1 in late 2008

    There are now over 50 Android phones According to Nielsenwire, Android now has 29% of the US

    Market share for smartphones (RIM has 27%; Apple has 27%)

    Android embraces open standards

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    6/160

    What is Android?

    Android is a software stack for mobile devices that includes an

    operating system, middleware and key applications.

    The Android SDK provides the tools and APIs necessary to

    begin developing applications on the Android platform using

    the Java programming language.

    http://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    7/160

    Android Features

    Application framework enabling reuse and replacement ofcomponents

    Dalvik virtual machine optimized for mobile devices

    Integrated browser based on the open source WebKit engine

    Optimized graphics powered by a custom 2D graphics library; 3D

    graphics based on the OpenGL ES 1.0 specification (hardwareacceleration optional)

    SQLite for structured data storage

    Media support for common audio, video, and still image formats(MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)

    GSM Telephony (hardware dependent)

    Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent)

    Rich development environment including a device emulator, toolsfor debugging, memory and performance profiling, and a plugin forthe Eclipse IDE

    http://webkit.org/http://webkit.org/
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    8/160

    Android Architecture

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    9/160

    Android Runtime

    Android includes a set of core libraries that provides most ofthe functionality available in the core libraries of the Javaprogramming language.

    Every Android application runs in its own process, with its owninstance of the Dalvik virtual machine. Dalvik has been writtenso that a device can run multiple VMs efficiently. The DalvikVM executes files in the Dalvik Executable (.dex) format whichis optimized for minimal memory footprint. The VM isregister-based, and runs classes compiled by a Java languagecompiler that have been transformed into the .dex format by

    the included "dx" tool. The Dalvik VM relies on the Linux kernel for underlying

    functionality such as threading and low-level memorymanagement.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    10/160

    Linux Kernel

    Android relies on Linux version 2.6 for core system services

    such as security, memory management, process management,

    network stack, and driver model. The kernel also acts as an

    abstraction layer between the hardware and the rest of the

    software stack.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    11/160

    Capabilities of Mobile Devices

    Internet access

    Touch screen

    GPS (global positioning system satellite-based system to

    determine a location)

    Local storage

    Camera

    Media playback

    Phone

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    12/160

    Limitation of Mobile Devices

    Screen size

    Touch screen

    Keyboard? Trackball?

    Memory

    Storage

    Battery Life

    Cell network

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    13/160

    Download the Android SDK

    http://developer.android.com/sdk/index.html

    Choose the file that corresponds to the platform that you will

    be developing on

    http://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    14/160

    Installing the SDK

    If you downloaded a .zip or .tgz package (instead of the SDK

    installer), unpack it to a safe location on your machine. By

    default, the SDK files are unpacked into a directory named

    android-sdk-.

    If you downloaded the Windows installer (.exe file), run it nowand it will check whether the proper Java SE Development Kit

    (JDK) is installed (installing it, if necessary), then install the SDK

    Tools into a default location (which you can modify).

    Make a note of the name and location of the SDK directory on

    your systemyou will need to refer to the SDK directory later,

    when setting up the ADT plugin and when using the SDK tools

    from command line.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    15/160

    Adding Platforms and

    Components The last step in setting up your SDK is using theAndroid SDK and AVD Manager(a tool

    included in the SDK starter package) to download essential SDK components into yourdevelopment environment.

    The SDK uses a modular structure that separates the major parts of the SDKAndroidplatform versions, add-ons, tools, samples, and documentationinto a set of separatelyinstallable components. The SDK starter package, which you've already downloaded,includes only a single component: the latest version of the SDK Tools. To develop anAndroid application, you also need to download at least one Android platform and the SDK

    Platform-tools (tools that the latest platform depend upon). However, downloadingadditional components is highly recommended.

    If you used the Windows installer, when you complete the installation wizard, it will launchthe Android SDK and AVD Manager with a default set of platforms and other componentsselected for you to install. Simply click Install to accept the recommended set ofcomponents and install them. You can then skip to Step 5, but we recommend you first readthe section about the Available Components to better understand the componentsavailable from the Android SDK and AVD Manager.

    You can launch the Android SDK and AVD Manager in one of the following ways: From within Eclipse, select Window > Android SDK and AVD Manager.

    On Windows, double-click the SDK Manager.exe file at the root of the Android SDKdirectory.

    On Mac or Linux, open a terminal and navigate to the tools/ directory in the Android SDK,then execute: android

    http://developer.android.com/sdk/installing.htmlhttp://developer.android.com/sdk/installing.htmlhttp://developer.android.com/sdk/installing.htmlhttp://developer.android.com/sdk/installing.htmlhttp://developer.android.com/sdk/installing.htmlhttp://developer.android.com/sdk/installing.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    16/160

    Android SDK and AVD

    Manager After launching the

    menu, select Availablepackages->AndroidRepository

    It is recommended toinstall all of theselected options

    Click the Install

    Selected button Installing all options

    could take a while

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    17/160

    Introducing Eclipse

    Eclipse is a popular opensource IDE used for Java, C,C++, and other programminglanguages

    Eclipse is supported onseveral platforms including

    Windows, Linux, and Mac Eclipse was created in 2001 by

    IBM

    Download it for free:http://eclipse.org/downloads,its recommended that you

    choose Eclipse Classic. Eclipse supports templates

    which allows it to beconfigured

    http://eclipse.org/downloadshttp://eclipse.org/downloadshttp://eclipse.org/downloads
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    18/160

    Configuring Eclipse

    Select a defaultlocation for yourprojects

    Eclipse calls this yourworkspace

    Typically, the defaultrecommendationfrom Eclipse is OKhowever, you cancustomize thelocation

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    19/160

    ADT Plugin

    The ADT Plugin is the Android Developer Template plugin

    The ADT Plugin configures Eclipse for Android software

    development

    It includes modifications to the text editor, installs simulators

    (modules to run your Android software on if you do not havean Android device), and other tools to assist with

    development tasks

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    20/160

    Installing the ADT Plugin

    Start Eclipse, then select Help > Install New Software....

    Click Add, in the top-right corner.

    In the Add Repository dialog that appears, enter "ADT Plugin"for the Name and the following URL for the Location:

    https://dl-ssl.google.com/android/eclipse/ Note: If you havetrouble acquiring the plugin, try using "http" in the LocationURL, instead of "https" (https is preferred for securityreasons).

    Click OK.

    In the Available Software dialog, select the checkbox next toDeveloper Tools and click Next.

    In the next window, you'll see a list of the tools to bedownloaded. Click Next.

    Read and accept the license agreements, then click Finish.

    When the installation completes, restart Eclipse.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    21/160

    Configuring the ADT Plugin

    Once you've successfully downloaded ADT as described

    above, the next step is to modify your ADT preferences in

    Eclipse to point to the Android SDK directory:

    Select Window > Preferences... to open the Preferences panel

    (Mac OS X: Eclipse > Preferences). Select Android from the left panel.

    For the SDK Location in the main panel, click Browse... and

    locate your downloaded SDK directory.

    Click Apply, then OK. Restart Eclipse.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    22/160

    Project One: Hello World

    It is a tradition tocreate Hello Worldas the first projectwhen learning a new

    platform This project will

    introduce the AndroidVirtual Device (AVD),using Eclipse, andverify that all of thesoftware we installedis working correctly

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    23/160

    Creating an AVD

    In this tutorial, you will run your application in the Android Emulator.Before you can launch the emulator, you must create an AndroidVirtual Device (AVD). An AVD defines the system image and devicesettings used by the emulator.

    To create an AVD:

    In Eclipse, choose Window > Android SDK and AVD Manager.

    Select Virtual Devices in the left panel.

    Click New.

    The Create New AVD dialog appears.

    Type the name of the AVD, such as "my_avd".

    Choose a target. The target is the platform (that is, the version of the

    Android SDK, such as 2.2) you want to run on the emulator. In the SD Card field, enter a size of 1024 MiB.

    You can ignore the rest of the fields for now.

    Click Create AVD.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    24/160

    Create a New Android Project

    After you've created an AVD, thenext step is to start a newAndroid project in Eclipse.

    1. From Eclipse, select File > New >Project. If the ADT Plugin forEclipse has been successfullyinstalled, the resulting dialog

    should have a folder labeled"Android" which should contain"Android Project". (After youcreate one or more Androidprojects, an entry for "AndroidXML File" will also be available.)

    2. Select "Android Project" and click

    Next.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    25/160

    Create a New Android Project

    (contd)1.Fill in the project

    details with thefollowing values: Project name:

    HelloAndroid

    Application name:Hello, Android

    Package name:com.example.helloandroid (or your ownprivate namespace)

    Create Activity:HelloAndroid

    2.Click Finish.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    26/160

    Package Explorer

    The Package Explorershows the layout ofyour Androidprojects.

    It allows you to viewthe source files,generated files, andother items you

    might use in a project(such as graphics,audio, etc.)

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    27/160

    HelloAndroid.java

    package com.example.helloandroid;

    import android.app.Activity;

    import android.os.Bundle;

    public class HelloAndroid extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout.main);

    }

    }

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    28/160

    Activity class

    public class HelloAndroid extends Activity

    Notice that the HelloAndroid class we created extends the

    Activity class.

    An Activity is a single application entity that is used to perform

    actions. An application may have many separate activities, but the user

    interacts with them one at a time.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    29/160

    OnCreate method

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    }

    The onCreate() method will be called by the Android system

    when your Activity starts it is where you should perform all

    initialization and UI setup. An activity is not required to have a

    user interface, but usually will.

    Now let's modify some code!

    http://developer.android.com/reference/android/app/Activity.htmlhttp://developer.android.com/reference/android/app/Activity.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    30/160

    Construct the UI

    package com.example.helloandroid;

    import android.app.Activity;import android.os.Bundle;import android.widget.TextView;

    public class HelloAndroid extends Activity {

    /** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);TextView tv = new TextView(this);tv.setText("Hello, Android");setContentView(tv);

    }

    } Add the bold, italic text to your HelloAndroid.java file.

    As you are typing, you will notice that Eclipse uses code completion this is ahandy feature of modern IDEs that can save a programmer time (and minimizelooking up specific methods a call, such as TextView, supports)

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    31/160

    Android Views

    An Android user interface is composed of hierarchies of objects calledViews. A View is a drawable object used as an element in your UI layout,such as a button, image, or (in this case) a text label. Each of theseobjects is a subclass of the View class and the subclass that handles textis TextView.

    In this change, you create a TextView with the class constructor, which

    accepts an Android Context instance as its parameter. A Context is ahandle to the system; it provides services like resolving resources,obtaining access to databases and preferences, and so on. The Activityclass inherits from Context, and because your HelloAndroid class is asubclass of Activity, it is also a Context. So, you can pass this as yourContext reference to the TextView.

    Next, you define the text content with setText().

    Finally, you pass the TextView to setContentView() in order to display itas the content for the Activity UI. If your Activity doesn't call thismethod, then no UI is present and the system will display a blankscreen.

    There it is "Hello, World" in Android! The next step, of course, is tosee it running.

    http://developer.android.com/reference/android/view/View.htmlhttp://developer.android.com/reference/android/view/View.htmlhttp://developer.android.com/reference/android/widget/TextView.htmlhttp://developer.android.com/reference/android/widget/TextView.htmlhttp://developer.android.com/reference/android/content/Context.htmlhttp://developer.android.com/reference/android/content/Context.htmlhttp://developer.android.com/reference/android/widget/TextView.htmlhttp://developer.android.com/reference/android/app/Activity.htmlhttp://developer.android.com/reference/android/app/Activity.htmlhttp://developer.android.com/reference/android/widget/TextView.htmlhttp://developer.android.com/reference/android/content/Context.htmlhttp://developer.android.com/reference/android/widget/TextView.htmlhttp://developer.android.com/reference/android/view/View.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    32/160

    Running Hello World

    The Eclipse plugin makes it easyto run your applications:

    Select Run > Run.

    Select "Android Application".

    The Eclipse plugin automaticallycreates a new run configurationfor your project and thenlaunches the Android Emulator.Depending on your environment,the Android emulator might takeseveral minutes to boot fully, soplease be patient. When theemulator is booted, the Eclipseplugin installs your application

    and launches the default Activity.You should now see somethinglike this:

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    33/160

    If Hello World doesnt run

    While working on this presentation, I could not get Hello

    Android to run. The emulator would start, but my app never

    installed

    I found this on the Android Portal:

    Quit the emulator if it is running Check that any emulator processes are killed (sometimes they

    can hang, use ps on unix or mac, or task manager in the process

    view on windows).

    Quit Eclipse

    From the command line, type: adb kill-server

    Start Eclipse and try again

    This solved the problem.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    34/160

    The AVD

    Home button

    Menu button

    Back button

    App button

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    35/160

    Eclipse Shortcuts

    Launch Wizards

    Android SDK and

    AVD Manager Android Debugger

    Run

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    36/160

    Eclipse Console

    The console is useful to see what is happening when you run

    your Android program

    It can show informational, warning, or error messages you

    might encounter

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    37/160

    Outside of class

    Hour 2: Mastering the Android Development Tools (in the

    SAMS Teach Yourself Android in 24 hours) is not covered in

    detail in this training session.

    It is recommended that you read over this chapter as it

    contains a lot of useful information.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    38/160

    What is an application?

    An application is a collection of tasks.

    Each task is called an activity.

    Each activity within an application has a unique purpose and

    user interface.

    Example game: Chippys Revenge has five screens

    Splash startup screen, game logo, sound

    Menu user can choose options to play game, view scores, read

    help

    Play The screen where the user plays the game Scores screen displays high scores

    Help screen displays instructions for playing the game

    l

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    39/160

    Application Activity

    Requirements Chippys Revenge would have five activity classes

    SplashActivity - This activity serves as the default activity to launch. Itsimply displays a layout (maybe just a big graphic), plays music forseveral seconds, and then launches MenuActivity.

    MenuActivityThis activity is pretty straightforward. Its layout hasseveral buttons, each corresponding to a feature of the application.

    The onClick() handlers for each button trigger cause the associatedactivity to launch.

    PlayActivityThe real application guts are implemented here. Thisactivity needs to draw stuff onscreen, handle various types of userinput, keep score, and generally follow whatever game dynamics thedeveloper wants to support.

    ScoresActivityThis activity is about as simple as SplashActivity. Itdoes little more than load a bunch of scoring information into aTextView control within its layout.

    HelpActivityThis activity is almost identical to ScoresActivity, exceptthat instead of displaying scores, it displays help text. Its TextViewcontrol might possibly scroll.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    40/160

    Application Context

    The application context is the central location for all top-level

    application functionality. You use the application context to

    access settings and resources shared across multiple activity

    instances.

    You can retrieve the application context for the currentprocess by using the getApplicationContext() method, like this:

    Context context = getApplicationContext();

    Because the Activity class is derived from the Context class,

    you can use this instead of retrieving the application context

    explicitly.

    Once you have retrieved a valid application context, you can

    use it to access application-wide features and services.

    R i i A li i

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    41/160

    Retrieving Application

    Resources You can retrieve application resources by using the

    getResources() method of the application context. The most

    straightforward way to retrieve a resource is by using its

    unique resource identifier, as defined in the automatically

    generated R.java class. The following example retrieves aString instance from the application resources by its resource

    ID:

    String greeting = getResources().getString(R.string.hello);

    A i A li i

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    42/160

    Accessing Application

    Preferences You can retrieve shared application preferences by using the

    getSharedPreferences() method of the application context.

    You can use the SharedPreferences class to save simple

    application data, such as configuration settings. Each

    SharedPreferences object can be given a name, allowing youcan organize preferences into categories or store preferences

    all together in one large set.

    For example, you might want to keep track of each users

    name and some simple game state information, such as

    whether the user has credits left to play. The following codecreates a set of shared preferences called GamePrefs and

    saves a few such preferences:

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    43/160

    Preferences Samples

    SharedPreferences settings =

    getSharedPreferences(GamePrefs, MODE_PRIVATE);

    SharedPreferences.Editor prefEditor = settings.edit();

    prefEditor.putString(UserName, Spunky);

    prefEditor.putBoolean(HasCredits, true);

    prefEditor.commit();

    To retrieve preference settings, you simply retrieve

    SharedPreferences and read the values back out:

    SharedPreferences settings =getSharedPreferences(GamePrefs, MODE_PRIVATE);

    String userName = settings.getString(UserName, Chippy Jr.

    (Default));

    A i O h A li i

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    44/160

    Accessing Other Application

    Functionality Using Contexts The application context provides access to a number of top-

    level application features. Here are a few more things you can

    do with the application context:

    Launch Activity instances

    Retrieve assets packaged with the application Request a system-level service provider (location service)

    Manage private application files, directories, and databases

    Inspect and enforce application permissions

    The most common use is launching Activity instances

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    45/160

    Working with Activities

    The Activity class is central to every Android application.

    Much of the time, youll define and implement an activity for

    each screen in your application.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    46/160

    Launching Activities

    There are a number of ways to launch an activity, including the

    following:

    Designation a launch activity in the manifest file

    Launching an activity using the application context

    Launching a child activity from a parent activity for a result

    D i ti L h A ti it

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    47/160

    Designating a Launch Activity

    in the Manifest file Each Android application must designate a default activity

    within the Android manifest file

    Inspect the file AndroidManifest.xml from the Hello Android

    project. Click on the Application tab, scroll down until you see

    Application Nodes. Note the default activity is HelloAndroid.

    L hi A ti iti U i th

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    48/160

    Launching Activities Using the

    Application Context The most common way to launch an activity is to use the

    startActivity() method of the application context. This method

    takes one parameter, called an intent. We will talk more about

    the intent in a moment, but for now, lets look at a simple

    startActivity() call.

    The following code calls the startActivity() method with an

    explicit intent:

    startActivity(new Intent(getApplicationContext(),

    MenuActivity.class));

    L hi A ti it f

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    49/160

    Launching an Activity for a

    Result Sometimes an activity wants to launch a related activity and

    get the result, instead of launching an entirely independent

    activity. In this case, you can use the

    Activity.startActivityForResult() method.

    The result will be returned in the Intent parameter of thecalling activitys onActivityResult() method.

    We will talk more about how to pass data using an Intent

    parameter in a moment.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    50/160

    Managing Activity State

    Applications can be interrupted when various higher-priority

    events, such as phone calls, take precedence.

    There can be only one active application at a time; specifically,

    a single application activity can be in the foreground at any

    given time. Your apps should prepare for the unexpected

    Save state

    Resume

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    51/160

    Activity Callbacks

    The Activity class has a number of callbacks that provide an

    opportunity for an activity to respond to events such as

    suspending and resuming.

    onCreate() called when an activity starts/restarts

    onResume() called when an activity becomes the foregroundactivity

    onPause() called when an activity leaves the foreground

    onDestroy() called when an application is shutting down

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    52/160

    Diagram of Callback Methods

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    53/160

    Working with Intents

    An intent is an abstract description of an operation to be

    performed.

    An Intent object encapsulates a task request used by the

    Android operating system.

    When the startActivity() method is called with the Intentparameter, the Android system matches the Intent action with

    appropriate activity on the Android system.

    That activity is then launched.

    Passing Information with

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    54/160

    Passing Information with

    Intents Intents can be used to pass data between activities. You can

    use an intent in this way by including additional data, called

    extras, within the intent.

    To package extra pieces of data along with an intent, you use

    the putExtra() method with the appropriate type of object youwant to include.

    The Android programming convention for intent extras is to

    name each one with the package prefix (for example,

    com.androidbook.chippy.NameOfExtra).

    Intent intent = new Intent(getApplicationContext(),HelpActivity.class);

    intent.putExtra(com.androidbook.chippy.LEVEL, 23);

    startActivity(intent);

    Using Intents to Launch Other

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    55/160

    Using Intents to Launch Other

    Applications Applications can launch external activity classes in other

    applications

    Examples:

    Launching the built-in web browser and supplying a URL address

    Launching the web browser and supplying a search string Launching the built-in Dialer application and supplying a phone

    number

    Launching the built-in Maps application and supplying a location

    Launching Google Street View and supplying a location

    Launching the built-in Camera application in still or video mode

    Launching a ringtone picker

    Recording a sound

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    56/160

    Intent Code Sample

    Uri address = Uri.parse(http://www.perlgurl.org);

    Intent surf = new Intent(Intent.ACTION_VIEW, address);

    startActivity(surf);

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    57/160

    Working with Dialogs

    Handset screens are small, and user interface real estate isvaluable.

    Sometimes you want to handle a small amount of user

    interaction without creating an entirely new activity.

    In such instances, creating an activity dialog can be veryhandy.

    Dialogs can be helpful for creating very simple user interfaces

    that do not necessitate an entirely new screen or activity to

    function.

    Instead, the calling activity dispatches a dialog, which can have

    its own layout and user interface, with buttons and input

    controls.

    Dialog Methods of the Activity

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    58/160

    Dialog Methods of the Activity

    Class Activity.showDialog() - Shows a dialog, creating it if necessary.

    Activity.onCreateDialog() - Is a callback when a dialog is being

    created for the first time and added to the activity dialog pool.

    Activity.onPrepareDialog() - Is a callback for updating a dialog

    on-the-fly. Dialogs are created once and can be used manytimes by an activity. This callback enables the dialog to be

    updated just before it is shown for each showDialog() call.

    Activity.dismissDialog() - Dismisses a dialog and returns to the

    activity. The dialog is still available to be used again by calling

    showDialog() again.

    Activity.removeDialog() - Removes the dialog completely from

    the activity dialog pool.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    59/160

    Outside of class

    Hour 4: Managing Application Resources (in the SAMS TeachYourself Android in 24 hours) is not covered in detail in this

    training session.

    Hour 5: Configuring the Android Manifest Files is not covered

    in detail in this training session It is recommended that you read over these chapters as they

    contain a lot of useful information.

    Project Two: Hello World

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    60/160

    Project Two: Hello World

    Advanced This project is a variation on project one.

    It introduces the Graphic Layout, resources, using a button,

    and seeing an alert

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    61/160

    Create a new project

    From Eclipse, File->New->Project

    From the Wizard

    screen, selectAndroid Project

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    62/160

    Examine R.java

    R.java is a generatedfile.

    Do not modify this

    file your changeswill be lost!

    This file has

    references to data

    used by apps such asicons, images,

    strings, etc.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    63/160

    Strings.xml

    Under the res folder,expand the values folder.

    Double-click on strings.xmlto all Eclipse to edit thefile.

    In the editor window, thereis a tab labeled Resourcesand another tab labeledstrings.xml.

    Resources is the simplerview it hides the XML

    data and shows thedefined strings.

    The strings.xml view is theraw XML.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    64/160

    Run the app

    Without making anycode changes, the

    app displays the

    message.

    Feel free to modify

    Strings.xml and

    experiment with

    different strings.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    65/160

    Main.xml

    Under the res folder,expand the layoutfolder.

    Double-click onmain.xml

    This will open theGraphical Layout editor

    Note the tabs at thebottom of the screen:

    Graphical Layout andmain.xml

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    66/160

    Lets add a button

    While in theGraphical Layoutmode, drag a Buttonobject to the view

    screen. Double-click on the

    Button this willcause Eclipse to go to

    the main.xml view. Change the text for

    Button to Alert

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    67/160

    Run the app

    You will see the button on the screen.

    If you click the button, nothing happens.

    Lets add some code to make something happen.

    Double-click on HelloWorldAndroid.java so we can make some

    changes.

    Lets make the button do

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    68/160

    Let s make the button do

    something Buttons must register with a Listener.

    A Listener detects specific events in a program such as a

    button press.

    We are using the OnClickListener() method when this is

    detected, we are then calling a method we create calledonClick().

    The onClick method executes some code.

    In the example we are implementing, we are going to use the

    Toast framework to display a Toast.

    A Toast is a short message that automatically exits once its

    timer expires.

    Sample code that implements

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    69/160

    Sample code that implements

    the onClick() method

    package com.test.helloworldadvanced;

    import android.app.Activity;

    import android.content.Context;

    import android.os.Bundle;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.Toast;

    public class HelloWorldAdvanced extends Activity {

    private Button alertButton;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    alertButton = (Button)this.findViewById(R.id.button1);

    alertButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

    Context context = getApplicationContext(); CharSequence text = "Hello toast!";

    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);

    toast.show();

    }

    });

    }

    }

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    70/160

    Run the app

    Pressing the Alertbutton will cause the

    Toast to display.

    Notice that the Toast

    exits after a few

    seconds without

    additional work.

    Toasts are often usedas informational

    messages or notices.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    71/160

    Project Three: Web views

    This project will introduce web views.

    Web views are used to view web pages and local HTML files

    (very useful for help files.)

    We will cover loading a web page from a URL and from a local

    HTML file.

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    72/160

    Create a new project

    Call the projectWebDemo

    Build Target: Android2.1-update1

    Application Name:WebDemo

    Package Name:com.test.webdemo

    Create Activity:WebDemo

    Min SDK Version: 7

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    73/160

    Edit res/layout/main.xml

    Remove the LinearLayout and TextView sections.

    Add the WebView section to your main.xml (copy/paste)

    t

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    74/160

    src/com.test.webdemo/WebD

    emo.java Below the line thatstarts with public

    class WebDemo,

    type WebView

    mWebView.

    WebView is the

    Android class for a

    web view. Notice the red X on

    the left hand side.

    Lets let the tools fix the

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    75/160

    Let s let the tools fix the

    problem Hover your mouse

    over the underlined

    text WebView

    You will see a pop-up

    that suggests some

    quick fixes.

    Select Import

    the error is resolved!

    Now modify the onCreate()

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    76/160

    Now, modify the onCreate()

    method public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled( true);

    mWebView.loadUrl("http://www.google.com");

    }

    This initializes the member WebView with the one from the

    Activity layout; requests a WebSettings object withgetSettings(); and enables JavaScript for the WebView withsetJavaScriptEnabled(boolean). Finally, an initial web page isloaded with loadUrl(String).

    Modify the

    http://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/app/Activity.htmlhttp://developer.android.com/reference/android/webkit/WebSettings.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebSettings.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebSettings.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebView.htmlhttp://developer.android.com/reference/android/webkit/WebSettings.htmlhttp://developer.android.com/reference/android/app/Activity.htmlhttp://developer.android.com/reference/android/webkit/WebView.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    77/160

    Modify the

    AndroidManifest.xml Because this application needs access to the Internet, you

    need to add the appropriate permissions to the Android

    manifest file. Open the AndroidManifest.xml file and add the

    following as a child of the element:

    While you're in the manifest, give some more space for web

    pages by removing the title bar, with the "NoTitleBar" theme:

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    78/160

    AndroidManifest.xml

    h

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    79/160

    Project Three Part Two

    This lab will expand the Web View so you can display HTMLfrom a local data source.

    Create a new project called WebViewFromFile

    Project Name: WebViewFromFile

    Build Target: Android 2.1-update1 Application Name: WebViewFromFile

    Package name: com.test.webviewfromfile

    Create Activity: WebViewFromFile

    Min SDK Version: 7

    l

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    80/160

    Eclipse note

    Note the PackageExplorer in Eclipse

    This allows you to

    manage multiple

    projects

    It is recommended

    you click the left

    hand arrow tocollapse projects we

    are not working on.

    M d f A d dM f l

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    81/160

    Modify AndroidManifest.xlm

    Since we are reading from a local html file, we technically donot need to add the permission

    android.permission.INTERNET

    It is a good practice to only give permissions that are required.

    To theme the browser, add the following:

    L i l HTML fil

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    82/160

    Lets create a simple HTML file

    In your project, go to the assets folder.

    Right-click on assets, select new file.

    For the file name, choose hello.html this creates an empty

    file.

    Right-click on hello.html, select Open With->Text Edit Type the following:

    Hello HTML

    Now, save the file.

    L dif i l

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    83/160

    Lets modify main.xml

    We are going to add aWebView to our project.Modifyres/layout/main.xml

    Click on the Graphical

    Layout tab On the left hand side,

    open the Compositefolder.

    Drag a WebView object

    to to interface screen onthe right hand side.

    (Remove any stray hellostrings if they exist)

    Cli k h i l b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    84/160

    Click on the main.xml tab

    Make not of the id.

    It will be similar to id=@+id/webkitWebView1

    Now, edit

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    85/160

    Now, edit

    WebViewFromFile.java

    package com.test.webviewfromfile;

    import android.app.Activity;

    import android.os.Bundle;

    import android.webkit.WebView;

    public class WebViewFromFile extends Activity {

    WebView browser;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    browser=(WebView)findViewById(R.id. webkitWebView1);

    browser.loadUrl("file:///android_asset/hello.html"); }

    }

    Notice how we set the URL for the browser. File:/// instructs the browser is is reading from a fileinstead of the internet.

    The android_asset tells it look in the asset folder for a file named hello.html.

    R th

    http://localhost/http://localhost/
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    86/160

    Run the program

    N t d T t i l

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    87/160

    Notepad Tutorial

    The next three projects cover the Notepad Tutorial from the Androiddeveloper portal

    Project Four: Construct a simple notes list that lets the user add

    new notes but not edit them. Demonstrates the basics of ListActivity

    and creating and handling menu options. Uses a SQLite database to

    store the notes. Project Five: Add a second Activity to the application. Demonstrates

    constructing a new Activity, adding it to the Android manifest,

    passing data between the activities, and using more advanced

    screen layout. Also shows how to invoke another Activity to return a

    result, using startActivityForResult(). Project Six: Add handling of life-cycle events to the application, to

    let it maintain application state across the life cycle.

    P j t F N t d 1

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    88/160

    Project Four: Notepad 1

    In this exercise, you will construct a simple notes list that letsthe user add new notes but not edit them. The exercise

    demonstrates:

    The basics of ListActivities and creating and handling menu

    options.

    How to use a SQLite database to store the notes.

    How to bind data from a database cursor into a ListView using

    a SimpleCursorAdapter.

    The basics of screen layouts, including how to lay out a list

    view, how you can add items to the activity menu, and how

    the activity handles those menu selections.

    St 1

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    89/160

    Step 1

    Open up the Notepadv1 project in Eclipse. Notepadv1 is a project that is provided as a starting point. It takes care of some

    of the boilerplate work that you have already seen if you followed the Hello,World tutorial.

    Start a new Android Project by clicking File > New > Android Project.

    In the New Android Project dialog, select Create project from existing source.

    Click Browse and navigate to where you copied the NotepadCodeLab

    (downloaded during setup) and select Notepadv1. The Project Name and other properties should be automatically filled for you.

    You must select the Build Targetwe recommend selecting a target with thelowest platform version available. Also add an integer to the Min SDK Versionfield that matches the API Level of the selected Build Target.

    Click Finish. The Notepadv1 project should open and be visible in your Eclipsepackage explorer.

    If you see an error about AndroidManifest.xml, or some problems related to anAndroid zip file, right click on the project and select Android Tools > Fix ProjectProperties. (The project is looking in the wrong location for the library file, thiswill fix it for you.)

    St 2

    http://developer.android.com/resources/tutorials/hello-world.htmlhttp://developer.android.com/resources/tutorials/hello-world.htmlhttp://developer.android.com/resources/tutorials/hello-world.htmlhttp://developer.android.com/resources/tutorials/hello-world.htmlhttp://developer.android.com/resources/tutorials/notepad/index.htmlhttp://developer.android.com/resources/tutorials/notepad/index.htmlhttp://developer.android.com/resources/tutorials/notepad/index.htmlhttp://developer.android.com/resources/tutorials/hello-world.htmlhttp://developer.android.com/resources/tutorials/hello-world.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    90/160

    Step 2a

    Take a look at the NotesDbAdapter class this class is provided toencapsulate data access to a SQLite database that will hold our notesdata and allow us to update it.

    At the top of the class are some constant definitions that will be used inthe application to look up data from the proper field names in thedatabase. There is also a database creation string defined, which is usedto create a new database schema if one doesn't exist already.

    Our database will have the name data, and have a single table callednotes, which in turn has three fields: _id, title and body. The _id isnamed with an underscore convention used in a number of places insidethe Android SDK and helps keep a track of state. The _id usually has tobe specified when querying or updating the database (in the columnprojections and so on). The other two fields are simple text fields thatwill store data.

    The constructor for NotesDbAdapter takes a Context, which allows it tocommunicate with aspects of the Android operating system. This is quitecommon for classes that need to touch the Android system in some way.The Activity class implements the Context class, so usually you will justpass this from your Activity, when needing a Context.

    St 2b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    91/160

    Step 2b

    The open() method calls up an instance of DatabaseHelper, which is our local implementation ofthe SQLiteOpenHelper class. It calls getWritableDatabase(), which handles creating/opening adatabase for us.

    close() just closes the database, releasing resources related to the connection.

    createNote() takes strings for the title and body of a new note, then creates that note in thedatabase. Assuming the new note is created successfully, the method also returns the row _idvalue for the newly created note.

    deleteNote() takes a rowIdfor a particular note, and deletes that note from the database.

    fetchAllNotes() issues a query to return a Cursor over all notes in the database. The query() call is

    worth examination and understanding. The first field is the name of the database table to query(in this case DATABASE_TABLE is "notes"). The next is the list of columns we want returned, in thiscase we want the _id, title and body columns so these are specified in the String array. Theremaining fields are, in order: selection, selectionArgs, groupBy, having and orderBy. Having theseall null means we want all data, need no grouping, and will take the default order. SeeSQLiteDatabase for more details.

    Note: A Cursor is returned rather than a collection of rows. This allows Android to use resourcesefficiently -- instead of putting lots of data straight into memory the cursor will retrieve andrelease data as it is needed, which is much more efficient for tables with lots of rows.

    fetchNote() is similar to fetchAllNotes() but just gets one note with the rowIdwe specify. It uses aslightly different version of the SQLiteDatabase query() method. The first parameter (set true)indicates that we are interested in one distinct result. The selection parameter (the fourthparameter) has been specified to search only for the row "where _id =" the rowIdwe passed in. Sowe are returned a Cursor on the one row.

    And finally, updateNote() takes a rowId, title and body, and uses a ContentValues instance toupdate the note of the given rowId.

    St 3

    http://developer.android.com/reference/android/database/Cursor.htmlhttp://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmlhttp://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmlhttp://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmlhttp://developer.android.com/reference/android/content/ContentValues.htmlhttp://developer.android.com/reference/android/content/ContentValues.htmlhttp://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmlhttp://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmlhttp://developer.android.com/reference/android/database/Cursor.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    92/160

    Step 3

    Open the notepad_list.xml file in res/layout and take a look atit. (You may have to hit thexmltab, at the bottom, in order toview the XML markup.)

    This is a mostly-empty layout definition file. Here are somethings you should know about a layout file:

    All Android layout files must start with the XML header line:.

    The next definition will often (but not always) be a layoutdefinition of some kind, in this case a LinearLayout.

    The XML namespace of Android should always be defined in

    the top level component or layout in the XML so that android:tags can be used through the rest of the file:xmlns:android="http://schemas.android.com/apk/res/android"

    St 4

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    93/160

    Step 4a

    We need to create the layout to hold our list. Add code inside of theLinearLayout element so the whole file looks like this:

    Step 4b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    94/160

    Step 4b

    The @ symbol in the id strings of the ListView and TextView tags meansthat the XML parser should parse and expand the rest of the id stringand use an ID resource.

    The ListView and TextView can be thought as two alternative views, onlyone of which will be displayed at once. ListView will be used when thereare notes to be shown, while the TextView (which has a default value of"No Notes Yet!" defined as a string resource in res/values/strings.xml)

    will be displayed if there aren't any notes to display. The list and empty IDs are provided for us by the Android platform, so,

    we must prefix the id with android: (e.g., @android:id/list).

    The View with the empty id is used automatically when the ListAdapterhas no data for the ListView. The ListAdapter knows to look for thisname by default. Alternatively, you could change the default empty view

    by using setEmptyView(View) on the ListView. More broadly, theandroid.R class is a set of predefined resources provided for you by theplatform, while your project's R class is the set of resources your projecthas defined. Resources found in the android.R resource class can beused in the XML files by using the android: name space prefix (as we seehere).

    Step 5

    http://developer.android.com/reference/android/widget/ListAdapter.htmlhttp://developer.android.com/reference/android/widget/AdapterView.htmlhttp://developer.android.com/reference/android/widget/AdapterView.htmlhttp://developer.android.com/reference/android/widget/ListAdapter.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    95/160

    Step 5

    To make the list of notes in the ListView, we also need to define a Viewfor each row:

    Create a new file under res/layout called notes_row.xml.

    Add the following contents (note: again the XML header is used, and thefirst node defines the Android XML namespace) This is the View that will be

    used for each notes title row it has only one text field in it.

    In this case we create a new id called text1. The + after the @ in the idstring indicates that the id should be automatically created as a resource

    if it does not already exist, so we are defining text1 on the fly and thenusing it.

    Save the file.

    Open the R.java class in the project and look at it, you should see newdefinitions for notes_row and text1 (our new definitions) meaning wecan now gain access to these from the our code.

    Step 6

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    96/160

    Step 6

    Next, open the Notepadv1 class in the source. In the following steps, we aregoing to alter this class to become a list adapter and display our notes, and alsoallow us to add new notes.

    Notepadv1 will inherit from a subclass of Activity called a ListActivity, which hasextra functionality to accommodate the kinds of things you might want to dowith a list, for example: displaying an arbitrary number of list items in rows onthe screen, moving through the list items, and allowing them to be selected.

    Take a look through the existing code in Notepadv1 class. There is a currently anunused private field called mNoteNumber that we will use to create numberednote titles.

    There are also three override methods defined: onCreate,onCreateOptionsMenu and onOptionsItemSelected; we need to fill these out:

    onCreate() is called when the activity is started it is a little like the "main"method for an Activity. We use this to set up resources and state for the activitywhen it is running.

    onCreateOptionsMenu() is used to populate the menu for the Activity. This isshown when the user hits the menu button, and has a list of options they canselect (like "Create Note").

    onOptionsItemSelected() is the other half of the menu equation, it is used tohandle events generated from the menu (e.g., when the user selects the "CreateNote" item).

    Step 7

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    97/160

    Step 7

    Change the inheritance of Notepadv1 from Activity toListActivity:

    public class Notepadv1 extends ListActivity Note: you will have

    to import ListActivity into the Notepadv1 class using Eclipse,

    ctrl-shift-O on Windows or Linux, or cmd-shift-O on the Mac

    (organize imports) will do this for you after you've written the

    above change.

    Step 8a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    98/160

    Step 8a

    Fill out the body of the onCreate() method. Here we will set the title for the Activity (shown at the top of the

    screen), use the notepad_list layout we created in XML, set up theNotesDbAdapter instance that will access notes data, and populate thelist with the available note titles:

    In the onCreate method, call super.onCreate() with thesavedInstanceState parameter that's passed in.

    Call setContentView() and pass R.layout.notepad_list.

    At the top of the class, create a new private class field called mDbHelperof class NotesDbAdapter.

    Back in the onCreate method, construct a new NotesDbAdapterinstance and assign it to the mDbHelper field (pass this into theconstructor for DBHelper)

    Call the open() method on mDbHelper to open (or create) the database.

    Finally, call a new method fillData(), which will get the data andpopulate the ListView using the helper we haven't defined thismethod yet.

    Step 8b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    99/160

    Step 8b

    onCreate() should now look like this: @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.notepad_list);

    mDbHelper = new NotesDbAdapter(this);

    mDbHelper.open();

    fillData();

    }

    And be sure you have the mDbHelper field definition (rightunder the mNoteNumber definition):

    private NotesDbAdapter mDbHelper;

    Step 9

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    100/160

    Step 9

    Fill out the body of the onCreateOptionsMenu() method. We will now create the "Add Item" button that can be accessed by pressing the menu

    button on the device. We'll specify that it occupy the first position in the menu.

    In strings.xml resource (under res/values), add a new string named "menu_insert" with itsvalue set to Add Item: Add Item Then save the fileand return to Notepadv1.

    Create a menu position constant at the top of the class: public static final int INSERT_ID =Menu.FIRST;

    In the onCreateOptionsMenu() method, change the super call so we capture the booleanreturn as result. We'll return this value at the end.

    Then add the menu item with menu.add().

    The whole method should now look like this:

    @Overridepublic boolean onCreateOptionsMenu(Menu menu) {

    boolean result = super.onCreateOptionsMenu(menu);menu.add(0, INSERT_ID, 0, R.string.menu_insert);

    return result;} The arguments passed to add() indicate: a group identifier for this menu (none, in thiscase), a unique ID (defined above), the order of the item (zero indicates no preference), andthe resource of the string to use for the item.

    Step 10

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    101/160

    Step 10

    Fill out the body of the onOptionsItemSelected() method: This is going to handle our new "Add Note" menu item. When this is selected, the

    onOptionsItemSelected() method will be called with the item.getId() set to INSERT_ID (theconstant we used to identify the menu item). We can detect this, and take the appropriateactions:

    The super.onOptionsItemSelected(item) method call goes at the end of this method wewant to catch our events first!

    Write a switch statement on item.getItemId(). In the case ofINSERT_ID, call a new method,

    createNote(), and return true, because we have handled this event and do not want topropagate it through the system.

    Return the result of the superclass' onOptionsItemSelected() method at the end.

    The whole onOptionsItemSelect() method should now look like this:

    @Overridepublic boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {case INSERT_ID:

    createNote();return true;}

    return super.onOptionsItemSelected(item);}

    Step 11

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    102/160

    Step 11

    Add a new createNote() method: In this first version of our application, createNote() is not going to be

    very useful. We will simply create a new note with a title assigned to itbased on a counter ("Note 1", "Note 2"...) and with an empty body. Atpresent we have no way of editing the contents of a note, so for now wewill have to be content making one with some default values:

    Construct the name using "Note" and the counter we defined in theclass: String noteName = "Note " + mNoteNumber++

    Call mDbHelper.createNote() using noteName as the title and "" for thebody

    Call fillData() to populate the list of notes (inefficient but simple) we'llcreate this method next.

    The whole createNote() method should look like this:

    private void createNote() {String noteName = "Note " + mNoteNumber++;mDbHelper.createNote(noteName, "");fillData();

    }

    Step 12a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    103/160

    Step 12a

    Define the fillData() method: This method uses SimpleCursorAdapter, which takes a

    database Cursor and binds it to fields provided in the layout.These fields define the row elements of our list (in this casewe use the text1 field in our notes_row.xml layout), so this

    allows us to easily populate the list with entries from ourdatabase.

    To do this we have to provide a mapping from the title field inthe returned Cursor, to our text1 TextView, which is done bydefining two arrays: the first a string array with the list of

    columns to mapfrom (just "title" in this case, from theconstant NotesDbAdapter.KEY_TITLE) and, the second, an intarray containing references to the views that we'll bind thedata into (the R.id.text1 TextView).

    Step 12b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    104/160

    Step 12b

    This is a bigger chunk of code, so let's first take a look at it: private void fillData() {

    // Get all of the notes from the database and create the item listCursor c = mDbHelper.fetchAllNotes();startManagingCursor(c);

    String[] from = new String[] { NotesDbAdapter.KEY_TITLE };int[] to = new int[] { R.id.text1 };

    // Now create an array adapter and set it to display using ourrow

    SimpleCursorAdapter notes =new SimpleCursorAdapter(this, R.layout.notes_row, c, from,

    to); setListAdapter(notes);}

    Step 12c

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    105/160

    Step 12c

    Here's what we've done: After obtaining the Cursor from mDbHelper.fetchAllNotes(), we use an Activity method

    called startManagingCursor() that allows Android to take care of the Cursor lifecycle insteadof us needing to worry about it. (We will cover the implications of the lifecycle in exercise 3,but for now just know that this allows Android to do some of our resource managementwork for us.)

    Then we create a string array in which we declare the column(s) we want (just the title, inthis case), and an int array that defines the View(s) to which we'd like to bind the columns(these should be in order, respective to the string array, but here we only have one for

    each). Next is the SimpleCursorAdapter instantiation. Like many classes in Android, the

    SimpleCursorAdapter needs a Context in order to do its work, so we pass in this for thecontext (since subclasses of Activity implement Context). We pass the notes_row View wecreated as the receptacle for the data, the Cursor we just created, and then our arrays.

    In the future, remember that the mapping between the from columns and to resources isdone using the respective ordering of the two arrays. If we had more columns we wantedto bind, and more Views to bind them in to, we would specify them in order, for example

    we might use { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY } and { R.id.text1,R.id.text2 } to bind two fields into the row (and we would also need to define text2 in thenotes_row.xml, for the body text). This is how you can bind multiple fields into a single row(and get a custom row layout as well).

    If you get compiler errors about classes not being found, ctrl-shift-O or (cmd-shift-O on themac) to organize imports.

    Step 13

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    106/160

    Step 13

    Run it! Right click on the Notepadv1 project.

    From the popup menu, select Run As > Android Application.

    If you see a dialog come up, select Android Launcher as the

    way of running the application (you can also use the link nearthe top of the dialog to set this as your default for the

    workspace; this is recommended as it will stop the plugin from

    asking you this every time).

    Add new notes by hitting the menu button and selectingAdd

    Item from the menu.

    Project 5: Notepad 2

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    107/160

    Project 5: Notepad 2

    In this exercise, you will add a second Activity to your notepadapplication, to let the user create and edit notes. You will also

    allow the user to delete existing notes through a context

    menu. The new Activity assumes responsibility for creating

    new notes by collecting user input and packing it into a return

    Bundle provided by the intent. This exercise demonstrates:

    Constructing a new Activity and adding it to the Android manifest

    Invoking another Activity asynchronously using

    startActivityForResult()

    Passing data between Activity in Bundle objects How to use a more advanced screen layout

    How to create a context menu

    Step 1

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    108/160

    Step 1

    Create a new Android project using the sources from Notepadv2 under theNotepadCodeLab folder, just like you did for the first exercise. If you see an errorabout AndroidManifest.xml, or some problems related to an android.zip file,right click on the project and select Android Tools > Fix Project Properties.

    Open the Notepadv2 project and take a look around:

    Open and look at the strings.xml file under res/values there are several newstrings which we will use for our new functionality

    Also, open and take a look at the top of the Notepadv2 class, you will noticeseveral new constants have been defined along with a new mNotesCursor fieldused to hold the cursor we are using.

    Note also that the fillData() method has a few more comments and now uses thenew field to store the notes Cursor. The onCreate() method is unchanged fromthe first exercise. Also notice that the member field used to store the notesCursor is now called mNotesCursor. The m denotes a member field and is part ofthe Android coding style standards.

    There are also a couple of new overridden methods (onCreateContextMenu(),onContextItemSelected(), onListItemClick() and onActivityResult()) which we willbe filling in below.

    Step 2a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    109/160

    Step 2a

    First, let's create the context menu that will allow users todelete individual notes. Open the Notepadv2 class.

    In order for each list item in the ListView to register for the

    context menu, we call registerForContextMenu() and pass it

    our ListView. So, at the very end of the onCreate() method add

    this line:

    registerForContextMenu(getListView());

    Because our Activity extends the ListActivity class,

    getListView() will return us the local ListView object for the

    Activity. Now, each list item in this ListView will activate thecontext menu.

    Step 2b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    110/160

    Step 2b

    Now fill in the onCreateContextMenu() method. This callback issimilar to the other menu callback used for the options menu. Here,we add just one line, which will add a menu item to delete a note.Call menu.add() like so:

    public void onCreateContextMenu(Menu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {

    super.onCreateContextMenu(menu, v, menuInfo);menu.add(0, DELETE_ID, 0, R.string.menu_delete);

    }

    The onCreateContextMenu() callback passes some otherinformation in addition to the Menu object, such as the View thathas been triggered for the menu and an extra object that may

    contain additional information about the object selected. However,we don't care about these here, because we only have one kind ofobject in the Activity that uses context menus. In the next step, we'llhandle the menu item selection.

    Step 3

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    111/160

    Step 3

    Now that the we've registered our ListView for a context menu anddefined our context menu item, we need to handle the callback when itis selected. For this, we need to identify the list ID of the selected item,then delete it. So fill in the onContextItemSelected() method like this: public boolean onContextItemSelected(MenuItem item) {

    switch(item.getItemId()) {case DELETE_ID:

    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();mDbHelper.deleteNote(info.id);fillData();return true;

    }return super.onContextItemSelected(item);

    }

    Here, we retrieve the AdapterContextMenuInfo with getMenuInfo().The idfield of this object tells us the position of the item in the ListView.We then pass this to the deleteNote() method of our NotesDbAdapterand the note is deleted. That's it for the context menu notes can nowbe deleted.

    Step 4a

    http://developer.android.com/reference/android/widget/AdapterView.AdapterContextMenuInfo.htmlhttp://developer.android.com/reference/android/view/MenuItem.htmlhttp://developer.android.com/reference/android/view/MenuItem.htmlhttp://developer.android.com/reference/android/widget/AdapterView.AdapterContextMenuInfo.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    112/160

    Step 4a

    Fill in the body of the createNote() method: Create a new Intent to create a note (ACTIVITY_CREATE) using

    the NoteEdit class. Then fire the Intent using the

    startActivityForResult() method call:

    Intent i = new Intent(this, NoteEdit.class);

    startActivityForResult(i, ACTIVITY_CREATE);

    This form of the Intent call targets a specific class in our

    Activity, in this case NoteEdit. Since the Intent class will need

    to communicate with the Android operating system to route

    requests, we also have to provide a Context (this).

    Step 4b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    113/160

    Step 4b

    The startActivityForResult() method fires the Intent in a waythat causes a method in our Activity to be called when the

    new Activity is completed. The method in our Activity that

    receives the callback is called onActivityResult() and we will

    implement it in a later step. The other way to call an Activity is

    using startActivity() but this is a "fire-and-forget" way ofcalling it in this manner, our Activity is not informed when

    the Activity is completed, and there is no way to return result

    information from the called Activity with startActivity().

    Don't worry about the fact that NoteEdit doesn't exist yet, wewill fix that soon.

    Step 5a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    114/160

    Step 5a

    Fill in the body of the onListItemClick() override. onListItemClick() is a callback method that we'll override. It is

    called when the user selects an item from the list. It is passed

    four parameters: the ListView object it was invoked from, the

    View inside the ListView that was clicked on, the position in

    the list that was clicked, and the mRowId of the item that was

    clicked. In this instance we can ignore the first two parameters

    (we only have one ListView it could be), and we ignore the

    mRowId as well. All we are interested in is the position that

    the user selected. We use this to get the data from the correct

    row, and bundle it up to send to the NoteEdit Activity.

    Step 5b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    115/160

    Step 5b

    In our implementation of the callback, the method creates an Intentto edit the note using the NoteEdit class. It then adds data into theextras Bundle of the Intent, which will be passed to the calledActivity. We use it to pass in the title and body text, and the mRowIdfor the note we are editing. Finally, it will fire the Intent using thestartActivityForResult() method call. Here's the code that belongs in

    onListItemClick(): super.onListItemClick(l, v, position, id);

    Cursor c = mNotesCursor;c.moveToPosition(position);Intent i = new Intent(this, NoteEdit.class);i.putExtra(NotesDbAdapter.KEY_ROWID, id);

    i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));

    i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));

    startActivityForResult(i, ACTIVITY_EDIT);

    Step 5c

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    116/160

    Step 5c

    putExtra() is the method to add items into the extras Bundleto pass in to intent invocations. Here, we are using the Bundle

    to pass in the title, body and mRowId of the note we want to

    edit.

    The details of the note are pulled out from our query Cursor,

    which we move to the proper position for the element that

    was selected in the list, with the moveToPosition() method.

    With the extras added to the Intent, we invoke the Intent on

    the NoteEdit class by passing startActivityForResult() the

    Intent and the request code. (The request code will bereturned to onActivityResult as the requestCode parameter.)

    Step 6a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    117/160

    Step 6a

    The above createNote() and onListItemClick() methods use anasynchronous Intent invocation. We need a handler for the callback, sohere we fill in the body of the onActivityResult().

    onActivityResult() is the overridden method which will be called whenan Activity returns with a result. (Remember, an Activity will only returna result if launched with startActivityForResult.) The parametersprovided to the callback are:

    requestCode the original request code specified in the Intentinvocation (either ACTIVITY_CREATE or ACTIVITY_EDIT for us).

    resultCode the result (or error code) of the call, this should be zero ifeverything was OK, but may have a non-zero code indicating thatsomething failed. There are standard result codes available, and you canalso create your own constants to indicate specific problems.

    intent this is an Intent created by the Activity returning results. It canbe used to return data in the Intent "extras."

    The combination of startActivityForResult() and onActivityResult() canbe thought of as an asynchronous RPC (remote procedure call) andforms the recommended way for an Activity to invoke another andshare services.

    Step 6b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    118/160

    Step 6b

    Here's the code that belongs in your onActivityResult(): super.onActivityResult(requestCode, resultCode, intent);

    Bundle extras = intent.getExtras();

    switch(requestCode) {case ACTIVITY_CREATE:

    String title = extras.getString(NotesDbAdapter.KEY_TITLE);String body = extras.getString(NotesDbAdapter.KEY_BODY);

    mDbHelper.createNote(title, body);fillData();break;

    case ACTIVITY_EDIT:Long mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);if (mRowId != null) {

    String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);String editBody = extras.getString(NotesDbAdapter.KEY_BODY);mDbHelper.updateNote(mRowId, editTitle, editBody);

    }fillData();break;

    }

    Step 6c

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    119/160

    Step 6c

    We are handling both the ACTIVITY_CREATE andACTIVITY_EDIT activity results in this method.

    In the case of a create, we pull the title and body from the

    extras (retrieved from the returned Intent) and use them to

    create a new note.

    In the case of an edit, we pull the mRowId as well, and use

    that to update the note in the database.

    fillData() at the end ensures everything is up to date .

    Step 7a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    120/160

    Step 7a

    Open the file note_edit.xml that has been provided and take a lookat it. This is the UI code for the Note Editor.

    This is the most sophisticated UI we have dealt with yet. The file isgiven to you to avoid problems that may sneak in when typing thecode. (The XML is very strict about case sensitivity and structure,mistakes in these are the usual cause of problems with layout.)

    There is a new parameter used here that we haven't seen before:android:layout_weight (in this case set to use the value 1 in eachcase).

    layout_weight is used in LinearLayouts to assign "importance" toViews within the layout. All Views have a default layout_weight ofzero, meaning they take up only as much room on the screen as theyneed to be displayed. Assigning a value higher than zero will split up

    the rest of the available space in the parent View, according to thevalue of each View's layout_weight and its ratio to the overalllayout_weight specified in the current layout for this and other Viewelements.

    Step 7b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    121/160

    Step 7b

    To give an example: let's say we have a text label and two text editelements in a horizontal row. The label has no layout_weight

    specified, so it takes up the minimum space required to render. If

    the layout_weight of each of the two text edit elements is set to 1,

    the remaining width in the parent layout will be split equally

    between them (because we claim they are equally important). If thefirst one has a layout_weight of 1 and the second has a

    layout_weight of 2, then one third of the remaining space will be

    given to the first, and two thirds to the second (because we claim

    the second one is more important).

    This layout also demonstrates how to nest multiple layouts inside

    each other to achieve a more complex and pleasant layout. In this

    example, a horizontal linear layout is nested inside the vertical one

    to allow the title label and text field to be alongside each other,

    horizontally.

    Step 8

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    122/160

    Step 8

    Create a NoteEdit class that extends android.app.Activity. This is the first time we will have created an Activity without the

    Android Eclipse plugin doing it for us. When you do so, the onCreate()method is not automatically overridden for you. It is hard to imagine anActivity that doesn't override the onCreate() method, so this should bethe first thing you do.

    Right click on the com.android.demo.notepad2 package in the Package

    Explorer, and select New > Class from the popup menu. Fill in NoteEdit for the Name: field in the dialog.

    In the Superclass: field, enter android.app.Activity (you can also justtype Activity and hit Ctrl-Space on Windows and Linux or Cmd-Space onthe Mac, to invoke code assist and find the right package and class).

    Click Finish.

    In the resulting NoteEdit class, right click in the editor window andselect Source > Override/Implement Methods...

    Scroll down through the checklist in the dialog until you seeonCreate(Bundle) and check the box next to it.

    Click OK.The method should now appear in your class.

    Step 9a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    123/160

    Step 9a

    Fill in the body of the onCreate() method for NoteEdit. This will set the title of our new Activity to say "Edit Note" (one of

    the strings defined in strings.xml). It will also set the content view touse our note_edit.xml layout file. We can then grab handles to thetitle and body text edit views, and the confirm button, so that ourclass can use them to set and get the note title and body, and attachan event to the confirm button for when it is pressed by the user.

    We can then unbundle the values that were passed in to the Activitywith the extras Bundle attached to the calling Intent. We'll use themto pre-populate the title and body text edit views so that the usercan edit them. Then we will grab and store the mRowId so we cankeep track of what note the user is editing.

    Inside onCreate(), set up the layout: setContentView(R.layout.note_edit);

    Change the Activity title to the "Edit Note" string:

    setTitle(R.string.edit_note);

    Step 9b

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    124/160

    Step 9b

    Find the EditText and Button components we need: These arefound by the IDs associated to them in the R class, and need

    to be cast to the right type of View (EditText for the two text

    views, and Button for the confirm button):

    mTitleText = (EditText) findViewById(R.id.title);

    mBodyText = (EditText) findViewById(R.id.body);

    Button confirmButton = (Button) findViewById(R.id.confirm);

    Note that mTitleText and mBodyText are member fields (you

    need to declare them at the top of the class definition).

    At the top of the class, declare a Long mRowId private field tostore the current mRowId being edited (if any).

    Step 9c

    http://developer.android.com/reference/android/widget/EditText.htmlhttp://developer.android.com/reference/android/widget/Button.htmlhttp://developer.android.com/reference/android/widget/Button.htmlhttp://developer.android.com/reference/android/widget/EditText.html
  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    125/160

    Step 9c

    Continuing inside onCreate(), add code to initialize the title, body andmRowId from the extras Bundle in the Intent (if it is present): mRowId = null;

    Bundle extras = getIntent().getExtras();if (extras != null) {

    String title = extras.getString(NotesDbAdapter.KEY_TITLE);String body = extras.getString(NotesDbAdapter.KEY_BODY);mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);

    if (title != null) {mTitleText.setText(title);

    }if (body != null) {

    mBodyText.setText(body);}

    }

    We are pulling the title and body out of the extras Bundle that was setfrom the Intent invocation.

    We also null-protect the text field setting (i.e., we don't want to set thetext fields to null accidentally).

    Step 9d

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    126/160

    Step 9d

    Create an onClickListener() for the button: Listeners can be one of themore confusing aspects of UI implementation, but what we are trying toachieve in this case is simple. We want an onClick() method to be calledwhen the user presses the confirm button, and use that to do somework and return the values of the edited note to the Intent caller. We dothis using something called an anonymous inner class. This is a bitconfusing to look at unless you have seen them before, but all you really

    need to take away from this is that you can refer to this code in thefuture to see how to create a listener and attach it to a button.(Listeners are a common idiom in Java development, particularly foruser interfaces.) Here's the empty listener:

    confirmButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {

    }

    });

    Step 10a

  • 7/31/2019 Chris Rider and Eric Rolf - Introduction to Android

    127/160

    p

    Fill in the body of the onClick() method of the OnClickListener created inthe last step.

    This is the code that will be run when the user clicks on the confirmbutton. We want this to grab the title and body text from the edit textfields, and put them into the return Bundle so that they can be passedback to the Activity that invoked this NoteEdit Activity. If the operationis an edit rather than a create, we also want to put the mRowId into the

    Bundle so that the Notepadv2 class can save the changes back to thecorrect note.

    Create a Bundle and put the title and body text into it using theconstants defined in Notepadv2 as keys: Bundle bundle = new Bundle();

    bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());

    bundle.putS