J2ME MIDP Currency Converter Tutorial for NetBeans IDE 4.0

Source: Internet
Author: User
Tags exit constructor copy int size numeric modifiers netbeans
J2ME MIDP Currency Converter Tutorial for NetBeans IDE 4.0
Feedback http://www.netbeans.org/kb/articles/tutorial-currencyconverter-40.html

Feedback


The Currency Converter application you are build in this tutorial shows you to:

Start a J2ME MIDP project
Code a working J2ME MIDP application, or MIDlet, using the IDE
Create project configurations to test the application ' s performance on two different device
The Currency Converter application converts amounts from one Currency to two. Can choose to display three different currencies:euros, yen, or dollars. You can also enter a value in one currency to being converted into the other selected currencies.

There are three Java source code files for the sample application:

Convertermidlet.java. The code for the MIDlet class.
Converter.java. A MIDP form that defines "main screen" the application as it appears on A mobile device.
Currencies Selector.java. A MIDP list that maintains the currencies and rates.
The "I" of this tutorial'll show you to quickly install, run, and test the Currency Converter application, WH The ICH is available as a sample project included the IDE. In the second part of the tutorial, you'll create a new project and add code to create and test the application yourself .

This tutorial should take approximately a hour to complete.

Requirements
You are must have NetBeans IDE 4.0 and the NetBeans Mobility Pack 4.0 installed before you can start J2ME MIDP development. The J2ME MIDP Development downloadpage for instructions on downloading and installing the complete.

Installing and testing the Sample Currency Converter Project
In this I, you'll have quickly you can install and run a sample project on two different emulator devices .

Creating the project Choose File > New project. Under Categories, select Samples > Mobile. Under Projects, select Currency Converter. Click Next.
The project name and Location page sets the name and Location of the project folder, and gives you the option of setting T He project as the main project. Click Next to accept the defaults.
The Platform Selection page sets the default execution environment, the emulator Platform, for the project. Note This default emulator platform is the J2ME Wireless Toolkit, and the default device is the Defaultcolorphone, a G Eneric mobile device. Click Finish to complete the wizard.
The Currency Converter displays in the Projects window.

Running the project Choose run > Run Main project.
The Currency Converter displays in the Defaultcolorphone Device Emulator.
Now "re ready to test the application in the Device Emulator.

Testing the application in the Defaultcolorphone screen, click the button under the word "Launch."
Select the currency you want to convert by clicking the-up ARROW keys
On the Select button. You can select dollars, Euros, or yen.
Enter the currency amount to convert by clicking the emulator ' s numeric keys.
The application makes the conversion calculations and displays the results.
Click the button underneath the word "exit" to exit the application.
Click the red button in the upper right corner to close the emulator.

Changing the Default emulator Device can create different project configurations to test your MIDlet on different Ator platforms, or simply change the device for the default configuration.

Choose File > "Currency Converter" Properties from the Main menu. In the Properties dialog, choose the Platform node. You can change the device for the default configuration.
Click the Device dropdown menu and choose Qwertydevice. Click OK.
Choose Run > Run Main Project Run the application again, and the application runs Qwertydevice in the emulator.


In the next part is tutorial, you'll start over, creating a new project. This would give you a opportunity to learn more about the code behind the application and I can use the IDE to code and test your own applications.

Creating the Currency Converter application
Creating the project Choose File > New project. Under Categories, select Mobile. Under Projects, select Mobile application. Click Next.
In the project name and Location page, name the project Newcurrencyconverter, and accept the default for project home. Leave the Set as main project check box checked, as you'll want this project to be your Main project Click Next.
Accept the defaults on the Platform page by clicking Finish.
The Newcurrencyconverter application displays in the Projects window.

Creating the Convertermidlet.java MIDlet
Choose File > New file. Under Categories, choose MIDP. Under File Types, choose MIDlet. Click Next.
In the name and Location page, Enter Currency Converter for the MIDlet Name, Convertermidlet for the MIDP Class name, and Myconverter for the package name.


Coding the MIDlet
Can write the code for a MIDlet in one of two ways:either by directly entering code in the Source Editor or by using The IDE to add methods, fields, constructors, initializers, classes, and interfaces. Typically, use the IDE to add new fields and methods to a class, or modify existing fields and methods, and then later Fine-tune the code directly in the Source Editor.
The following procedure shows you with the tool and the Source Editor to enter or change code. However, to save time and effort, your can also copy the converter code from the example your installed.

Coding the Convertermidlet.java MIDlet in the Source Editor, add the following import statements to Convertermidlet.java:

Import Java.io.*;import javax.microedition.rms.*;
In the Projects Tab, expand the Convertermidlet node, right-click the Convertermidlet class and choose Add > Field.
This next step would use the Add New Field dialog box to add the field storeddatastr to the MIDlet. The STOREDDATASTR string contains the name of the RMS stored record.
Complete the ADD New Field dialog box:
Enter the name of the new field, Storeddatastr, in the Name box and select
Its type, String, from the type combo box.
In the Modifiers box, select the type of access for the field, private, from the
Access combo box.
Check the other modifiers for the field and which in the ' case ' is static.
Set the initial value for Storeddatastr to "Converterdata".
Click OK to close the dialog box.
The field is added to the code in the Source Editor window.

Add the following fields to the Convertermidlet.java class using the Source Editor.
You can use the Add Field dialog box, copy the text from this page, or from the installed Currency Converter application, and paste it in the Source Editor. Be careful, however, not to change the package name from Myconverter.

public class Convertermidlet extends Javax.microedition.midlet.MIDlet {private static String Storeddatastr = "Converterd ATA ";
Public string[] Currencies = new string[] {"US $", "yen \u00a5", "Euro \u20ac"}; Public boolean[] selected = new boolean[] {True, True, true, true}; Public long[][] Rates = {1000000, 117580000, 911079}, {8504, 1000000, 7749},
{1097600, 129056000, 1000000}}; Private RecordStore Storeddata;
ADD the following code to the method StartApp (). This is called the application is started. It loads all of the data (currencies, selected currencies, and exchange rates) from persistent storage and initially The Converter form. The method should look like this:

public void startApp () {try {
Storeddata = Recordstore.openrecordstore (Storeddatastr, true);
if (storeddata.getnumrecords () > 0) {
DataInputStream in = new DataInputStream (New Bytearrayinputstream (Storeddata.getrecord (1))); try {int size = In.readint (); currencies = new String[size]; selected = new Boolean[size]; rates = new long[size][]; for (int i=0; i<size; i++) {Currencies[i] = In.readutf (); Selected[i] = In.readboolean (); rates[i] = new long[size]; for (int j=0; j<size; J + +) { RATES[I][J] = In.readlong ();
} }
In.close (); catch (IOException IoE) {}} catch (Recordstoreexception e) {} notifysettingschanged (); }
The Destroyapp () is called to application is finished, or destroyed. ADD the following code to complete the Destroyapp () method:

public void Destroyapp (Boolean unconditional) {try {bytearrayoutputstream bytes = new Bytearrayoutputstream (); DataOutputStream out = new DataOutputStream (bytes); try {out.writeint (currencies.length); for (int i=0; i<currencies.length; i++) {Out.writeutf (currencies[i)); Out.writeboolean (Selected[i]); for (int j=0; j<currencies.length; J + +) {Out.writelong (rates[i][j]);} Out.close (); if (storeddata.getnumrecords () > 0) Storeddata.setrecord (1, Bytes.tobytearray (), 0, Bytes.size ()); Else Storeddata.addrecord (Bytes.tobytearray (), 0, Bytes.size ()); catch (IOException IoE) {ioe.printstacktrace ();}} catch (Recordstoreexception e) {e.printstacktrace ();} notifydestroyed (); }
ADD The following three new methods:
Showsettings ()
This method creates and displays the Currenciesselector list.

public void Showsettings () {
Display.getdisplay (This). Setcurrent (The new Currenciesselector (this));
}
Notifysettingschanged ()
This method displays a new Converter form after the settings are changed.

public void notifysettingschanged () {Display.getdisplay (this). Setcurrent (The new Converter (this));
Longconvert ()
This method performs the currency conversion. The input value, Frval, is multiplied by the exchange rate stored in the rates table and divided by 1,000,000. The FRIDX and TOIDX values are the indexes of the source and target currencies.

Public long convert (long frval, int fridx, int toidx) {return (Frval * RATES[FRIDX][TOIDX])/1000000;
8. Save the Convertermidlet by choosing File > Save.


Creating a MIDP Form
Now so you have completed the code for the MIDlet and you'll create the application ' graphical interface. A form is a Java class this can contain an arbitrary mixture of items, including images, read-only and editable text field s, editable date fields, gauges, choice groups, and custom items. The form you create here'll specify a text box for each selected currency and specify the Itemstatelistener () method to M Onitor and reflect typed values and perform conversions.

Coding the Converter.java MIDP Form
In the Projects window, right-click the Myconverter package. Choose File > New file/folder.
The New File Wizard opens.
Under Categories, expand MIDP, then expand MIDP Forms. Under File Types Choose MIDP Form. Click Next.
In the name and Location page, enter Converter for the class Name. Click Finish.
A MIDP form is created and added to the Myconverter package.
In the Source Editor, add the following fields to the code below the public class Converter declaration:

Private Convertermidlet midlet;private int[] translate;
ADD the following code to complete the constructor and so it looks like the sample below:

Public Converter (Convertermidlet MIDlet) {super ("Currency Converter");
This.midlet = MIDlet; This.translate = new Int[midlet.currencies.length]; int current = 0; for (int i=0; i<translate.length; i++) {if (midlet.selected[i)) {translate[current++] = i; append (new TextField (midle T.currencies[i], "", Textfield.numeric);} The try {//Set up this form to the listen to command the events Setcommandlistener (this);//The Set up here form to listen to changes I n the internal state of it interactive items setitemstatelistener (this); ADD The Currencies Command AddCommand (New command ("currencies", Command.ok, 1)); Add the Exit command AddCommand (New command ("Exit", Command.exit, 1));
catch (Exception e) {e.printstacktrace ();}
}

ADD the following code to complete the "Method Commandaction" (), so it looks like the sample below:
public void commandaction (Command command, displayable displayable) {if (command.getcommandtype () = = Command.exit) {MIDL Et.destroyapp (TRUE); else if (command.getcommandtype () = = Command.ok) {midlet.showsettings ();}
}
ADD the following code to complete the Itemstatechanged () method, so it looks like the sample below:
public void Itemstatechanged (item) {try {Long value = Long.parselong ((TextField) Item). getString ()); int from = 0; while (from)!= item) from++; from = Translate[from]; for (int i=0; i<size (); i++) {int to = Translate[i]; if (from!= to) {(TextField) get (i)). SetString (mi Dlet.convert (value, from, to)); {for (int i=0; I<size (), i++) {(TextField) get (i)). SetString ("") (NumberFormatException NFE)}

This completes the Converter.java form file.


Creating a MIDP List
The final piece of the Currency Converter application is the Currenciesselector.java list file, which defines the Currenci Es that can is
Selected for display.

Coding the Currenciesselector.java MIDP List
In the Projects window, right-click the Myconverter package. Choose File > New file/folder.
The New File Wizard opens.
Under Categories, expand MIDP, then expand MIDP Forms. Under File Types Choose MIDP List. Click Next.
In the name and Location page, enter Currenciesselector for the class Name. Click Finish.
A MIDP list file is created and added to the Myconverter package.
After the line public class Currenciesselector extends List implements Commandlistener {, declare a field:

Private Convertermidlet MIDlet;
ADD the following code to complete the constructor and so it looks like the sample below:

Public Currenciesselector (Convertermidlet MIDlet) {Super ("Select Currencies", List.multiple, midlet.currencies, NULL) ; This.midlet = MIDlet; Setselectedflags (midlet.selected); try {//Set up this list to listen to command events Setcommandlistener (this);//ADD The Save command AddCommand (new Com Mand ("Save", Command.ok, 1)); catch (Exception e) {e.printstacktrace ();}}
ADD the following code to complete the "Method Commandaction" (), so it looks like the sample below:
public void commandaction (Command command, displayable displayable) {if (command.getcommandtype () = = Command.ok) {GetSel Ectedflags (midlet.selected); Midlet.notifysettingschanged (); } }
This completes the Currenciesselector.java list file.


Testing Your Application
Now this you have created your application, can test it with different emulator devices, as you did with the sample Cu Rrency Converter Project you in the installed. However, instead of switching the emulator device in the default configuration, this time you'll create a second project Configuration for the Qwertydevice Device Emulator.

Creating a New Project Configuration
Choose File > "Newcurrencyconverter" Properties.
Click the Manage configurations button.
The Project Configuration Manager opens.
Click the Add Button.
The ADD Configuration button displays.
Name the new configuration Qwertydevice. Click Ok.
Click close to close the Project Configuration Manager.
You are have a second configuration, Qwertydevice, that has the same properties as the defaultconfiguration.

Changing the Device property while still in the Project Properties, choose Platform from the "Tree menu" in "the left pane of The window.
If It Qwertydevice is isn't shown as the active project configuration, choose it from the project configuration dropdown U.
So it can choose new values for this configuration, uncheck the ' Use values from defaultconfiguration ' check box.
Choose Qwertydevice from the Device dropdown menu. Click OK.

Running the application on Both configurations make sure this Configuration dropdown menu on the toolbar lists Default Configuration as the active project Configuration.
Choose Run > Run Main Project.
The Currency Converter opens in the Defaultcolorphone Device emulator.
Choose Qwertydevice from the Configuration dropdown menu in the toolbar.
Choose Run > Run Main Project.
The Currency Converter opens in the Qwertydevice Device emulator.
Now you can test and compare the application's performance on different devices in the same time.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.