June 24, 2018
Hot Topics:

Building a J2ME Application in NetBeans 4.1

  • August 11, 2005
  • By Dick Wall
  • Send Email »
  • More Articles »

Adding the Rest

You are getting close now, but you have two major items left to add. The first is the functionality—updating the totals, doing the calculations, displaying the results, and so forth.

The second equally important one is to store and load the data. When you shut down your mileage calculator, you don't want to lose the data, so it has to be stored in the device memory somewhere.

Add the functionality code first, and then worry about persisting the data afterwards.

Adding the Functionality

The first thing you need in your application is some fields to store the data, both the totals and the averages:

  1. In the Projects pane (top left), expand out the tree until you can see your MileageMidlet (if it is not expanded already), and then expand that. You should see four nodes: Fields, Constructors, Methods, and Bean Patterns.
  2. You are going to add properties through the Bean Patterns node (the fastest way to add properties).
  3. First, right-click on Bean Patterns and select Add Property.
  4. For the name, type startingMileageVal, type is long, and mode is Read/Write. Leave all the other settings as default and click OK.
  5. Repeat for long properties currentMileageVal, totalMileageVal, totalFuelVal, totalCostVal, avgMpgVal, and avgCostVal.

Note that all the fields are added as long, not float. This is because in CLDC 1.0, floating point is not a part of the spec. You will be using fixed-point arithmetic to 2DP of accuracy for this example. You can use CLDC 1.1 in your project spec, which includes floating point support, but make sure your device supports it (my series 40 Nokia does not).

The solution using fixed-point arithmetic is to make some simplifying assumptions. For example, you will deal only with whole miles for the mileage (this will even out over time because you enter the vehicle's current mileage, not the difference since the last re-fuelling. Secondly, you will assume that the gallons and cost are entered using hundredths of gallons (with no decimal point) and in cents. In other words, instead of entering 12.43 gallons, you will enter 1243; and instead of $20.98, you will enter 2098. This makes it easier to type in using the phone keypad, and also keeps things nice and easy to manipulate in integers. When you calculate the summaries for the summary screen, you will use integer division and modulo to show the formatted gallons with two decimal places of accuracy.

Still with me? Yes, this is a compromise, but the art of writing Java ME applications involves a fair amount of compromise. Alternatives would be to allow a string to be entered into the numeric fields, then parse out the integer information from that, or use CLDC 1.1 and go for full floating point (just watch that you have support from your target devices). Either way, these are left as an exercise for the reader for the sake of brevity.

Okay, so you now have your fields. You can add some functionality to use them:

  1. From the Flow Design screen, double-click on the Add Details form to bring up the device screen.
  2. You will see the screen, but you should also see two assigned commands to the right of it. This is where you can attach the functionality.
  3. On the OK Command (probably named okCommand2), click the edit link.
  4. There are two editable areas: pre-action user code and post-action user code. Not surprisingly, these can contain code that happens either prior to the action of switching to another form, or after it. You are going to put some functionality in the Pre-Action user code section.
  5. There are really two ways to do this: You can put all the code you want in the editable section, but if you do so you will not get Intellisense help, so I prefer the other option. You will create a new method called this.updateDetails() and simply call it from this pre-action. So, in the text area, simply type this.updateDetails(); and click OK.
  6. Next, you have to supply the code for the updateDetails() method.
  7. In the Projects pane, right-click on the Methods node for the MileageMidlet and select Add Method.
  8. Name the method (of course) updateDetails. Leave the return type void and the parameters empty.
  9. This will create the method; double-click on the new method in the Projects pane to edit the body.
  10. Note: Alternatively to the above, if you prefer you could simply jump straight to the source and create the new method by typing it in there. It might be quicker.
  11. Add the following code to the body of the updateDetails method:.
    this.currentMileageVal =
    int currentGallons =
    int currentCost = Integer.parseInt(this.cost.getString());
    // figure out new totals
    this.totalMileageVal = this.currentMileageVal
                         - this.startingMileageVal;
    this.totalCostVal += currentCost;
    this.totalFuelVal += currentGallons;
  13. YOu also need to define the recalcAveragesAndUpdateSummary() method. Either repeat the method definition procedure above from the Projects pane, or just add the method in the editor window. The method should be:
    public void recalcAveragesAndUpdateSummary() {
       // fixed point arithmetic - keep everything multiplied
       // by a factor of 100
       // Need to protect against division by 0
       if(this.totalMileageVal == 0) {
          this.avgCostVal = 0;
       } else {
          this.avgCostVal = this.totalCostVal
                          / this.totalMileageVal;
       if(this.totalFuelVal == 0) {
          this.avgMpgVal = 0;
       else {
          // Note: 10000 multiplier is to take into account Fuel
          // 100 multiplier and another 100 to add 2 DP to average
          this.avgMpgVal = (this.totalMileageVal * 10000)
                         / this.totalFuelVal;
       // Temporary String to hold formatted values
       String tempFormat = null;
       // set the current mileage just by converting to String
       // For avg cost - format as 23 cents
       tempFormat = Long.toString(this.avgCostVal) + " cents";
       // and fixed point also for MPG
       tempFormat = Long.toString(this.avgMpgVal / 100) + "." +
          Long.toString(this.avgMpgVal % 100);

Next, you need to fill in the Initialization code. This is quite simple now that you have done the above work:

  1. From the Flow Design, double-click on the InitializeForm and then Edit the OK command.
  2. In the Pre-Action user code, enter this.initializeTotalsAndAverages();.
  3. Click OK.
  4. Create a new method:
    public void initializeTotalsAndAverages() {
       this.startingMileageVal =
       this.currentMileageVal  = this.startingMileageVal;
       this.totalMileageVal    = 0;
       this.totalCostVal       = 0;
       this.totalFuelVal       = 0;
  6. Save all and rebuild.

Okay, that's the functionality in place; as simple as it is. You can now debug the app again and try it out. Initialize it with a starting mileage and then add some details. Pretend you have filled up after 300 miles or something. You should see the summary details update when you OK the new details. Don't forget to enter gallons multiplied by a factor of 100 (1243 for 12.43 gallons) and cost in cents (2065 for $20.65).

There is, however, one last missing piece. When you quit the app right now, all data is lost. You need a way to persist it. Fortunately, the persistence mechanism provided in Java ME is dead simple.

Page 3 of 5

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date