The many faces of Android emulator
in the Eclipse IDE via the ADT plug-in. The majority of our focus is on employing the Android emulator from Eclipse, but you’re encouraged to examine the command-line options available in the emulator because they’ll undoubtedly be of value as you progress to building more complex Android applications, your application testing requirements grow, and you enlist other developers/testers to exercise your application.
Speaking of applications, let’s set up one – a very handy tip calculator!
Android sample application code
Our goal with the Android tip calculator is to permit our user to enter the price of a meal, then tap a button to calculate the total cost of the meal, tip included. To accomplish this, we need to modify two
Listing 2. ChapterTwo.java implements the tip calculator logic
package com.manning.unlockingandroid; #1
Instance();
import com.manning.unlockingandroid.R;
// grab the input meal price
import android.app.Activity; #2
fmp = nf.parse(mealprice).floatVal
import android.util.Log;
// let's give a nice tip -> 20%
public class ChapterTwo extends Activity {
Log.i(tag,"Total Meal Price
import java.text.NumberFormat;
ue();
fmp *= 1.2;
// some imports omitted
public static final String tag = "Chapter2";
(unformatted) is [" + fmp + "]");
@Override
// format our result
public void onCreate(Bundle icicle) {
answer = "Full Price, Including
super.onCreate(icicle);
20% Tip: " + nf.format(fmp);
setContentView(R.layout.main);
// display the answer
final EditText mealpricefield =
(EditText) findViewById(R.id.mealpr
answerfield.setText(answer);
#7
ice); #3
Log.i(tag,"onClick complete.");
final TextView answerfield =
} catch (java.text.ParseException pe)
(TextView) findViewById(R.id.answ
{ #8
er);
Log.i(tag,"Parse exception
id.calculate);
answerfield.setText("Failed to
final Button button = (Button) findViewById(R.
caught");
button.setOnClickListener(new
parse amount?");
} catch (Exception e) {
Button.OnClickListener() { #4
public void onClick(View v) {
Log.e(tag,"Failed to Calculate
Try {
Tip:" + e.getMessage());
e.printStackTrace();
//Perform action on click Log.i(tag,"onClick invoked."); #5
answerfield.setText(e.getMessage(
// grab the meal price from the UI String mealprice =
mealpricefield.getText().toString( ); #6
Log.i(tag,"mealprice is [" + mealprice + "]");
String answer = "";
// check to see if the meal price includes a "$" if (mealprice.indexOf("$") == -1) {
mealprice = "$" + mealprice; }
float fmp = 0.0F;
// get currency formatter NumberFormat nf =
}
}
});
}
}
));
#1 Package name
#2 Required imports
#3 Reference EditText for mealprice #4 Set up onClick Listener #5 Log entry
#6 Get meal price
#7 Display full price, including tip #8 Catch parse error
java.text.NumberFormat.getCurrency
02/2010 (20)
37