Skip to main content

Networking MIDlets and blocking operations

Posted by qmahmoud on April 18, 2007 at 12:41 PM PDT

I get many email about the application featured in the article MIDP Database Programming with RMS. The application locks up the screen as the MIDlet tries to establish a wireless connection. This article was developed back in 2000 and back then everything worked perfectly. However, when developing networking MIDlets, pay special attention to blocking operations (e.g. methods that establish a connection to the network) which can lock up the screen, leaving the user frustrated with the application. To prevent this, all blocking operations should be performed in a separate thread. A more detailed explanation of this can be found in Preventing Screen Lockups of Blocking Operations in which I provide a detailed example of a network time MIDlet client.

To fix the problem in the Stock Quotes MIDlet from the MIDP Database Programming article, edit the QuotesMIDlet.java file, and:

  1. Create a new method as follows:
    public void makeConnection() {
       try {
          String userInput = input.getString();
          String pr = getQuote(userInput);
          db.addNewStock(pr);
          ticker.setString(tickerString());
       } catch(IOException e) {
       } catch(NumberFormatException nfe) {
       }
       mainMenu();
    }
    
  2. Replace the following piece of code:
    } else if (label.equals("Save")) {
       if(currentMenu.equals("Add")) {
          // add it to database
          try {
             String userInput = input.getString();
             String pr = getQuote(userInput);
             db.addNewStock(pr);
             ticker.setString(tickerString()); 
          } catch(IOException e) {
          } catch(NumberFormatException se) {
          }
          mainMenu();
       } 
    }
    

    with:

    } else if (label.equals("Save")) {
       if(currentMenu.equals("Add")) {
          Thread t = new Thread() {
             public void run() {
                makeConnection();
             }
          };
          t.start();
       }
    }
    

And this should solve the screen lockup problem. :-)

There will be lots of Java ME cool stuff at JavaOne this year. To get an idea of what's planned for then, take a look at Terrence Barr's Java ME Guide to JavaOne 2007. Q.

Related Topics >>