Try Listener

//Perform action on click

Log. i (tag, "onClick invoked."); <1—© Log entry / / grab the meal price from the UI String mealprice =

mealpricefield.getText().toString(); <-© Get meal price

Log.i(tag,"mealprice is [" + mealprice + "]"); String answer = "";

// check to see if the meal price includes a "$" if (mealprice.indexOf("$") == -1) { mealprice = "$" + mealprice;

// get currency formatter

NumberFormat nf =

j ava.text.NumberFormat.getCurrencylnstance();

// grab the input meal price fmp = nf.parse(mealprice).floatValue();

Log. i (tag, "Total Meal Price (unformatted) is [" + fmp + "] ") ; // format our result answer = "Full Price, Including 20% Tip: " + nf.format(fmp)

/ / display the answer answerfield.setText(answer);

I Display full price,

Q inc

Log.i (tag, "onClick complete."); h mdudmg tip

Log.i (tag, "Parse exception caught"); i Catch parse error answerfield.setText("Failed to parse amount?"); } catch (Exception e) { Log.e(tag,"Failed to Calculate Tip:" + e.getMessage()); e.printStackTrace();


Let's examine this sample application, step-by-step. Like all but the most trivial Java applications, this class contains a statement identifying which package it belongs to: com.manning.unlockingandroid O- This line containing the package name was generated by the Application Wizard.

We import the com.manning.unlockingandroid.R class to gain access to the definitions used by the UI. Note that this step is not actually required because the R class is part of the same application package; however, it is helpful to include this import because it makes our code easier to follow. Also note that there are some built-in UI elements in the R class. Some are introduced later in the book as part of sample applications.

A number of imports are necessary C to resolve class names in use; most of the import statements have been omitted from this code listing for the sake of brevity. One import that is shown here contains the definition for the java.text.NumberFormat class, which is used to format and parse currency values.

Another import shown is for the android.util.Log class, which is employed to make entries to the log. Calling static methods of the Log class adds entries to the log. Entries in the log may be viewed via the LogCat view of the DDMS Perspective. When making entries to the log, it is helpful to put a consistent identifier on a group of related entries using a common string, commonly referred to as the tag. We can filter on this string value so we don't have to sift through the hundreds and thousands of LogCat entries to find our few debugging or informational messages.

We connect the UI element containing mealprice to a class-level variable of type EditText d by calling the findViewById method, passing in the identifier for the mealprice, as defined by our automatically generated R class, found in With this reference, we can access the user's input and manipulate the meal price data as entered by the user. Similarly, we connect the UI element for displaying the calculated answer back to the user, again by calling the findViewById method.

To know when to calculate the tip amount, we need to obtain a reference to the Button so we can add an event listener. We want to know when the button has been clicked. We accomplish this by adding a new OnClickListener method named onClick O.

When the onClick method is invoked, we add the first of a few log entries using the static i() method of the Log class f. This method adds an entry to the log with an Information classification. The Log class contains methods for adding entries to the log for different levels, including Verbose, Debug, Information, Warning, and Error.

Now that we have a reference to the mealprice UI element, we can obtain the text entered by our user with the getText() method of the EditText class g. In preparation for formatting the full meal price, we obtain a reference to the static currency formatter.

Let's be somewhat generous and offer a 20 percent tip. Then, using the formatter, let's format the full meal cost, including tip. Next, using the setText() method of the TextView UI element named answerfield, we update the UI to tell the user the total meal cost O.

Because this code might have a problem with improperly formatted data, it is a good practice to put code logic into Try/Catch blocks to keep our application behaving when the unexpected occurs ©.

There are additional files in this sample project, but in this chapter we are concerned only with modifying the application enough to get custom functionality working. You will notice that as soon as we save our source files, the Eclipse IDE compiles the project source files in the background. If there are any errors, they are listed in the Problems view of the Java Perspective as well as marked in the left-hand margin with a small red x to draw our attention to them.

Using the command-line tools found in the Android SDK, you can create batch builds of your applications without the use of the IDE. This approach is useful for software shops with a specific configuration-management function and a desire to conduct automated builds. In addition to the Android-specific build tools found under the tools subdirectory of your Android SDK installation, you will also require a Java Developer Kit (JDK) version 5.0 or later in order to complete command-line application builds. Automating builds of Android applications is beyond the scope of this book; however, you can learn more about the topic of build scripts by reading two Manning titles on the topic: Java Development with Ant by Erik Hatcher and Steve Loughran found at http: // and Ant in Action, Second Edition of Java Development with Ant, by Steve Loughran and Erik Hatcher, found at

Assuming there are no errors in the source files, our classes and UI files will compile properly. But what needs to happen before our project can be run and tested in the Android Emulator?

0 0

Post a comment