RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Obtaining Wireless News with J2ME and PHP : Page 3

J2ME and PHP are both powerful technologies used to develop applications for mobile devices and Web applications, respectively. In this article, you'll see how to make them work together by developing a simple and useful application that retrieves the latest news from the Web and displays that on a mobile device.

The NewsFetcher Class
Finally, the NewsFetcher class is responsible for downloading the articles from the Web on a separate thread to maintain the responsiveness of the user interface (see Listing 2).

Note the form of the URL field, for example:

On my PC, I set the Apache Web Server to listen on port 8000 because I already had IIS listening on the default port 80. However, you'll need to change the URL string to an appropriate value for your environment. Then, when uploading the PHP files to a "real" Web Server, you will have to change the URL string to a form like this:

The core method of NewsFetcher is getNews, as shown below:

   private void getNews() throws IOException {
      InputStream is = null;
      StringBuffer sb = new StringBuffer();
      HttpConnection http = null;
      try {
         //append the channel name onto the URL
         URL += "?channel=" + channelName;
         //replace not allowed chars in the URL
         URL = encodeURL(URL);
         //establish the connection
         http = (HttpConnection) Connector.open(URL);
         //set the request method as GET
         //server response
         if(http.getResponseCode() == HttpConnection.HTTP_OK) {
            int ch;
            is = http.openInputStream();
            while((ch = is.read()) != -1)
               sb.append((char) ch);
      catch (Exception e) {
         System.err.println("Error: " + e.toString());
      finally {
         if(is != null)
         if(sb != null)
            news = new String(sb);
            news = new String();
         if(http != null)
      Vector v;
      //extract titles and descriptions from the news
      if(news != "") { //success
         //for debug purpose only
         v = (new NewsParser(news)).parse();
         midlet.showTitles(v, true, channelName);
      else { //failure
         v = new Vector();
         midlet.showTitles(v, false, channelName);
This method tries to establish an HTTP connection (type HttpConnection). It first appends the request string to the URL; then it calls the encodeURL method, which encodes the URL, replacing any characters not allowed in a URL string. The core part of the method tries to establish the actual connection with the URL, sets the request method to GET and checks the response from the server. If the response is OK, the method passes the string returned by the response to the showTitles method that you saw in the WirelessNews class.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date