FeaturesPluginsDocs & SupportCommunityPartners

How to create and use Mobile Class Library with NetBeans 4.0

This tutorial will teach you how to crete a new mobile class library with NetBeans 4.0 and how to use your library in other projects. In this tutorial we will make a general HttpUtil library that can be used to load web server pages easily with just one method.

The project includes only one source code file:

  • HttpUtil.java, The HttpUtil class
  • Requirements

    You must have NetBeans IDE 4.0 and the NetBeans Mobility Pack 4.0 installed before you can start J2ME MIDP development. See the J2ME MIDP Development Download page for instructions on downloading and installing the complete environment.

    Creating a Mobile Class Library project

    Create a new Mobile Class Library project

    1. Choose File > New project (Ctrl-Shift-N). Under Categories, select Mobile

    2. Select Mobile Class Library under Projects. Click Next.

    3. Under Project Name, type HttpUtil.

    4. Change the Project Location to any folder on your computer.

    5. Click Finish.

    Create the source file

    1. Right-click the HttpUtil project node in Projects window and select New > Java Class

    2. Under Class Name, type HttpUtil.

    3. Under Package, type org.me.http

    4. Click Finish.

    5. Now you have a default source code for HttpUtil class. Right click on HttpUtil.java file and select Open.

    6. Define your class by copying and pasting the following code over the existing default code:

    7.   /*
         * HttpUtil.java
         */
      
        package org.me.http;
      
        import javax.microedition.io.*;
        import java.io.*;
      
        /**
         *
         * Basic HTTP utility.
         * Class provides static method for HTTP GET request.
         *
         */
        public class HttpUtil {
      
            /** send a GET request to web server */
            public static String sendGetRequest(String url)
                    throws IOException {
      
                HttpConnection hc = null;
                DataInputStream dis = null;
                String response = "";
      
                try {
                    /**
                     * Open an HttpConnection with the Web server
                     * The default request method is GET
                     */
                    hc = (HttpConnection) Connector.open(url);
      
                    /**
                     * Get a DataInputStream from the HttpConnection
                     */
                    dis = new DataInputStream(hc.openInputStream());
      
                    /**
                     * Read the content from requested page
                     */
                    int ch;
                    while ((ch = dis.read()) != -1) {
                        response = response + (char) ch;
                    }
                } finally {
                    if (hc != null) hc.close();
                    if (dis != null) dis.close();
                }
                return response;
            }
        }
      


    Building the project

    Build the Mobile Class Library

    1. Right-click the HttpUtil project node in the projects window and choose Build Project from contextual menu.

    2. The HttpUtil.jar file is created in the dist folder.


    Using Mobile Class Library in other Mobile projects

    Create new Mobile Application project

    1. Choose File > New project (Ctrl-Shift-N). Under Categories, select Mobile

    2. Select Mobile Application under Projects. Click Next.

    3. Under Project Name, type HttpTest.

    4. Change the Project Location to any folder on your computer.

    5. Deselected Create Hello MIDlet checkbox

    6. Click Finish.

    Add a reference to HttpUtil class

    1. Right-click the HttpTest project node in Projects window and select Properties

    2. Select Build / Libraries & Resources in properties tree

    3. Click Add Jar/Zip

    4. You could also add the whole NetBeans project to this project's resource. This way the HttpUtil project would be build every time you would build the HttpTest project.

    5. Browse into HttpUtil project's dist folder and open HttpUtil.jar file

    6. Close properties windown by clicking OK button.

    Create MIDlet class

    1. Right-click the HttpTest project node in Projects window and select New > MIDlet

    2. Under MIDlet Name, type HttpTestMidlet

    3. Under MIDP Class Name, type HttpTestMidlet

    4. Under Package, type org.me.httptest

    5. Click Finish.

    6. Define your class by copying and pasting the following code over the existing default code:

    7.   package org.me.httptest;
      
        import javax.microedition.midlet.*;
        import javax.microedition.lcdui.*;
        import org.me.http.*;
      
        public class HttpTestMidlet extends MIDlet
                implements CommandListener, Runnable {
      
            Form        m_urlForm;              // The URL form
            Form        m_pageForm;             // The data form
            TextField   m_url;                  // The URL text box
            Command     m_sendRequestCommand;   // The send command
            Command     m_backCommand;          // The back command
            Command     m_exitCommand;          // The exit command
            Display     m_display;              // The display
            Thread      m_netThread;            // The networking thread
            boolean     m_request;              // The equest flag
      
            public void startApp() {
                m_urlForm = new Form("URL");
                m_pageForm = new Form("Page");
                m_sendRequestCommand = new Command("Send request", Command.SCREEN, 1);
                m_backCommand = new Command("Back", Command.SCREEN, 1);
                m_exitCommand = new Command("Exit", Command.SCREEN, 2);
                m_url = new TextField("Enter URL", "http://", 64, TextField.URL);
                m_urlForm.addCommand(m_sendRequestCommand);
                m_urlForm.addCommand(m_exitCommand);
                m_urlForm.append(m_url);
                m_pageForm.addCommand(m_backCommand);
                m_netThread = new Thread(this);
                m_display = Display.getDisplay(this);
                m_urlForm.setCommandListener(this);
                m_display.setCurrent(m_urlForm);
                m_netThread.start();
                m_request = false;
            }
      
            public void pauseApp() {
            }
      
            public void destroyApp(boolean unconditional) {
            }
      
            public void run(){
                try{
                    while(true){
                        if(m_request){
                            m_pageForm.deleteAll();
                            m_pageForm.append("Downloading...");
                            try{
                                String data = HttpUtil.sendGetRequest(m_url.getString());
                                m_pageForm.deleteAll();
                                m_pageForm.append( data );
                            }catch(Exception e){
                                m_pageForm.append("Error occured: " + e.toString());
                            }
                            m_request = false;
                        }
                        else{
                            m_netThread.sleep(1000);
                        }
                    }
                }
                catch(InterruptedException e){
                }
            }
      
            public void commandAction(Command c, Displayable s) {
                if( c == m_sendRequestCommand ){
                    m_pageForm.setCommandListener( this );
                    m_display.setCurrent(m_pageForm);
                    m_request = true;
                }
                if( c == m_backCommand ){
                    m_urlForm.setCommandListener( this );
                    m_display.setCurrent(m_urlForm);
                }
                if( c == m_exitCommand ){
                    destroyApp(false);
                    notifyDestroyed();
                }
            }
        }
      

    Build and run the application

    1. Choose Run > Run Main Project (F6).

    2. The emulator launches. Next steps are performed in emulator.

    3. Launch the HttpTestMidlet.

    4. Enter URL address, eg. http://www.netbeans.org.

    5. Choose Menu > Send request.

    6. After a while the NetBeans website's content is presented in a form as a html code.


    The end

    Conclusion and development ideas

    This concludes the Mobile Class Library tutorial, but you may easily continue on developing this framework. You could for example code a RSS (Really Simple Syndication) parser and create a RSS client to your mobile device.

    Bookmark this page

    del.icio.us furl simpy slashdot technorati digg
    Companion
    Projects:
    MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Open ESB - The Open Enterprise Service Bus Powered by