Showing posts with label Nokia. Show all posts
Showing posts with label Nokia. Show all posts

Wednesday, 7 November 2012

RssFeed Reader in J2me(LWUIT)

This article Contains the Code to read an RssFile in j2me.After execution ,You can able to display the Title and an Image on Nokia Screen

The Midlet Class:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sun.lwuit.*;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import java.util.Vector;
import javax.microedition.midlet.*;
/**
 * @author pavan
 */
public class RssMidlet extends MIDlet implements ActionListener {
    private List rssFeedList;
    private Vector rssFeed;
    private Image image;
    private Form form1;
    private Command cmdExit, cmdDetails;
//Constructor 
      public RssMidlet() {
        Display.init(this);
        rssFeed = new Vector();
        cmdExit = new Command("Exit");
        cmdDetails = new Command("Details");
        form1 = new Form();
        form1.addCommand(cmdDetails);
        form1.addCommand(cmdExit);
        form1.setFocus(true);
        form1.addCommandListener(this);
        form1.setScrollableY(true);
        form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
        rssFeedList = new List(rssFeed);
        rssFeedList.setRenderer(new NewsListCellRenderer());
        rssFeedList.setFixedSelection(List.FIXED_NONE);
        rssFeedList.setItemGap(0);
        form1.addComponent(rssFeedList);
        } 
         public void startApp() {
        String url = "rss URL";
        ParseThread myThread = new ParseThread(this);
        //this will start the second thread
         myThread.getXMLFeed(url);
          } 
      public void pauseApp() {
       }
                 public void destroyApp(boolean unconditional) {
        }
                 public void DisplayError(Exception error) {
        Dialog validDialog = new Dialog("Alert");
        validDialog.setScrollable(false);
        validDialog.setScrollable(false);
        // set timeout milliseconds
        validDialog.setTimeout(5000);
        //pass the alert text here
        TextArea textArea = new TextArea(error.getMessage());
        textArea.setFocusable(false);
        textArea.setScrollVisible(false);
        validDialog.addComponent(textArea);
        validDialog.show(0, 100, 10, 10, true);
        }
       public void addNews(RssModel newsItem) {
        rssFeed.addElement(newsItem);
        //to handle actions on the list we need to set the actionListener
        rssFeedList.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                List source = (List) ae.getSource();
            }
          });
        form1.show();
         }
    public void actionPerformed(ActionEvent ae) {
        if (ae.getCommand() == cmdExit) {
            destroyApp(true);
            notifyDestroyed();
           }
          }
           }
A Model Class:
import com.sun.lwuit.Image;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pavan
 */
public class RssModel {
 
    private String title;
    private Image image;
    public RssModel(String title){
        this.title=title;
       // this.image=image;
     
    }
 
    public String getTitle(){
        return title;
    }
    /* public Image getImage(){
        return image;
    }
    * */
 
   }
 RssParsing Class:
import com.sun.lwuit.Image;
import org.kxml2.io.*;
import java.io.*;
import javax.microedition.io.*;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParser;
public class ParseThread {
    protected RssMidlet parentMidlet;
    private Image image;
    private String title;
    public ParseThread(RssMidlet parent) {
        parentMidlet = parent;
    }
    public void getXMLFeed(final String url) {
        Thread t = new Thread() {
            public void run() {
                HttpConnection myConnection = null;
                try {
                    myConnection = (HttpConnection) Connector.open(url);


                    InputStream stream = myConnection.openInputStream();
                    ParseXMLFeed(stream);
                } catch (Exception error) {
                    parentMidlet.DisplayError(error);
                } finally {
                    try {
                        if (myConnection != null) {
                            myConnection.close();
                        }
                    } catch (IOException eroareInchidere) {
                        parentMidlet.DisplayError(eroareInchidere);
                    }
                }
            }
        };
        t.start();
    }
    private void ParseXMLFeed(InputStream input)
            throws IOException, XmlPullParserException {
        InputStreamReader isr = new InputStreamReader(input);
        KXmlParser myParser = null;
        try {
            myParser = new KXmlParser();

            myParser.setInput(isr);
            myParser.nextTag();
            System.out.println("nextTag");
            myParser.require(XmlPullParser.START_TAG, null, "rss");
            myParser.nextTag();
            myParser.require(XmlPullParser.START_TAG, null, "channel");
            myParser.nextTag();
            myParser.require(XmlPullParser.START_TAG, null, "title");
        } catch (Exception e) {
        }
        while (myParser.getEventType() != XmlPullParser.END_DOCUMENT) {
            String name = myParser.getName();
            if (name.equals("channel")) {
                break;
            }
            if (name.equals("item")) {
                if (myParser.getEventType() != XmlPullParser.END_TAG) {
                    myParser.nextTag();
                    title = myParser.nextText();
                    //myParser.nextTag();
                    // String link = myParser.nextText();
                    // myParser.nextTag();
                    // String imageurl = myParser.nextText();
                    // ImageClass ic = new ImageClass();
                    // image = ic.getImage(parentMidlet, imageurl.trim());

                    RssModel model = new RssModel(title);
                    parentMidlet.addNews(model);
                }
            } else {
                myParser.skipSubTree();
            }
            myParser.nextTag();
           }
         input.close();
           }
          }
Finally
NewsListCellRenderer :
You can Create this class by Referring This URL(Just Copy the ContactsRenderer Class File)
Here is the Sample:

public class NewsListCellRenderer extends Container implements ListCellRenderer {
      public NewsListCellRenderer() {  }
    public Component getListCellRendererComponent(List list, Object value, int i, boolean bln)              {}    
}

Thanks.........................





Wednesday, 24 October 2012

HTML Text Extraction in J2me

This article will helps you to Extract a Text from a Html Stringin J2me using HtmlComponent.You need to Provide the Input as Html String to this Sample Example.Then the output will be Pure Text.

Check the Sample Code Below:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.html.HTMLComponent;
import javax.microedition.midlet.MIDlet;
/**
 * @author pavan
 */
public class HtmlMidlet extends MIDlet {
    public void startApp() {
        Display.init(this);
        Form f = new Form("HtmlComponent");
        String html = "<p>HTMl Text Extraction </P><p>Html Text Extraction</p>";
        HTMLComponent com = new HTMLComponent();
        com.setBodyText(html);
        f.addComponent(com);
        f.show();
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
     }
     }

Note:
1)If you have an Image tag in Html String.Then you can also display  an Image on Screen by Using the below Statement
//com.setShowImages(true);
2)To execute the above Application you need LWUIT jar file.You can download the jar file Here

Creating a HyperLink in j2me

This article will  helps you to display a Hyperlink on (LCDUI User Interface) Form Screen for a WebURL.

If an user clicks on the link it will opens the Hyperlink on  a Phone Default Browser.

You Can find the Complete Code Below:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
 * @author pavan
 */
public class HyperLinkMidlet extends MIDlet {
     String url = "http://www.google.com";
    private Display display;
    private StringItem stringItem;
    private Form form;
     Command com ;
    public HyperLinkMidlet() {
        form = new Form("HyperLink");
                com = new Command("Set", Command.ITEM, 1);
        stringItem = new StringItem("Click Here: ", "Set", Item.HYPERLINK);
    }
    public void startApp() {
        display = Display.getDisplay(this);
         stringItem.setText(url);
        stringItem.setDefaultCommand(com);
        form.append(stringItem);
        display.setCurrent(form);  
        stringItem.setItemCommandListener(new ItemCommandListener() {
            public void commandAction(Command c, Item item) {
                if (c == com) {
                    try {
                        platformRequest(url);
                    } catch (ConnectionNotFoundException ex) {
                    }
                }
            }
        });
 
       }
        public void pauseApp() {
         }
       public void destroyApp(boolean unconditional) {
      }
 
      }

Monday, 22 October 2012

Nokia(j2me) RssFeed(XML) Reader Application using LCDUI(UserInterface API)

This article will helps you to develope  an RssFeed Reader (XML) for Nokia Mobile.
If you run this Application Initially, you will be able to display a (LCDUI User Interface)List Screen.

On this List Screen you will be displayed with an Image as well as a title from Rss-xml file.Moreover,if you click on any List Item you will be Navigate to a Form Screen.

You can Check the Complete Code Below:
Package Structure:


RssMidlet  Class:


import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class RssMidlet extends MIDlet implements CommandListener {
    private Display myDysplay;
    private List rssList;
    private Vector rssItem;
    private Command cmdExit, cmdDetails;
    private Command m_backCommand;      // The back to header list command
    private Form form;         // The item form
    private RssModel model;
    public RssMidlet() {
        rssItem= new Vector();
        form=new Form("FormScreen");
       
        myDysplay = Display.getDisplay(this);
        m_backCommand = new Command("Back", Command.SCREEN, 1);
        form.addCommand(m_backCommand);
        rssList = new List("RssListScreen", List.IMPLICIT);
        cmdExit = new Command("EXIT", Command.EXIT, 1);
        cmdDetails = new Command("Details", Command.SCREEN, 2);
        rssList.addCommand(cmdExit);
        rssList.addCommand(cmdDetails);
       }
   
                 public void startApp() {
        // XML file url
        String url = "Rss File Here";
        form.setCommandListener(this);
        rssList.setCommandListener(this);
        ParseThread myThread = new ParseThread(this);
        //this will start the second thread
        myThread.getXMLFeed(url);
        Display.getDisplay(this).setCurrent(rssList);
       }
        public void pauseApp() {
        }
        public void destroyApp(boolean unconditional) {
       }
     
public void commandAction(Command command, Displayable displayable) {
        /**
         * Get back to RSS feed headers
         */
        if (command == m_backCommand) {
            myDysplay.setCurrent(rssList);
        }
        if (command == cmdExit) {
            destroyApp(false);
            notifyDestroyed();
        } else if (command == cmdDetails || command == List.SELECT_COMMAND) {
            //get the index of the selected title
            int index = rssList.getSelectedIndex();
            if (index != -1) {
                           Display.getDisplay(this).setCurrent(form);     
            }
             
             
        }
    }
    //method called by the parsing thread
    public void addItems(RssModel model) {
        rssItem.addElement(rssItem);
       
        rssList.append(model.getTitle(), model.getImage());
     
        myDysplay.setCurrent(rssList);
    }
    public void DisplayError(Exception error) {
        Alert errorAlert = new Alert("Error", error.getMessage(), null, null);
        errorAlert.setTimeout(Alert.FOREVER);
        myDysplay.setCurrent(errorAlert, rssList);
    }
}

ParseThread:
import org.kxml2.io.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.Image;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParser;
              public class ParseThread {
    protected RssMidlet parentMidlet;
    private String imageurl;
    private Image image;
    private String readUrl;
    private String srcUrl;
    public ParseThread(RssMidlet parent) {
        parentMidlet = parent;
    }
    public void getXMLFeed(final String url) {
        Thread t = new Thread() {
            public void run() {
                HttpConnection myConnection = null;
                try {
                    myConnection = (HttpConnection) Connector.open(url);
                    InputStream stream = myConnection.openInputStream();
                    ParseXMLFeed(stream);
                } catch (Exception error) {
                    parentMidlet.DisplayError(error);
                } finally {
                    try {
                        if (myConnection != null) {
                            myConnection.close();
                        }
                    } catch (IOException eroareInchidere) {
                        parentMidlet.DisplayError(eroareInchidere);
                    }
                }
            }
        };
        t.start();
    }
             private void ParseXMLFeed(InputStream input) throws IOException, XmlPullParserException {
        System.out.println("ParseXMLFeed");
        Reader dataReader = new InputStreamReader(input);
        KXmlParser myParser = null;
        try {
            myParser = new KXmlParser();
        } catch (Exception e) {
            //System.out.println("hiiii" + e);
        }
        myParser.setInput(dataReader);

        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "rss");
        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "channel");
        myParser.nextTag();
        myParser.require(XmlPullParser.START_TAG, null, "title");
        while (myParser.getEventType() != XmlPullParser.END_DOCUMENT) {
            String name = myParser.getName();
            if (name.equals("channel")) {
                break;
            }
            if (name.equals("item")) {
                if (myParser.getEventType() != XmlPullParser.END_TAG) {
                    myParser.nextTag();
                    String title = myParser.nextText();
                    System.out.println("Title" + title);
                    myParser.nextTag();
                    String link = myParser.nextText();
                    System.out.println("Link" + link);
                    myParser.nextTag();
                    String pubDate = myParser.nextText();
                    myParser.nextTag();
                    String ptext = myParser.nextText();//(<p>some text</p>)
                    System.out.println("PTEXT>>>" + ptext);
                            //Image src Value from ptext  
                    if (ptext.indexOf("src") != -1) {
                        int pTagIndex = ptext.indexOf("p");
                        int srcIndex1 = ptext.indexOf("src", pTagIndex);
                        int httpIndex1 = ptext.indexOf("/", srcIndex1);
                        int quotesIndex1 = ptext.indexOf("\"", httpIndex1);
                        srcUrl = ptext.substring(httpIndex1, quotesIndex1);
                        System.out.println("srcUrl " + srcUrl);
                        boolean containsWhitespace = srcUrl.trim().indexOf(" ") != -1;
                        if (containsWhitespace == true) {
                            displayDefaultImage();

                        } else {
                            //imageurl = "http://www...." + srcUrl;
                         
                            ImageClass ic = new ImageClass();
                            image = ic.getImage(parentMidlet, srcUrl.trim());
                        }

                    } else {
                        System.out.println("Default");
                        displayDefaultImage();
                    }
                    //check imagesrc contains any whitespace characters or not
                    RssModel model = new RssModel(title, image);
                    parentMidlet.addItems(model);
                    }
                     } else {
                     myParser.skipSubTree();
                      }
                    myParser.nextTag();
                       }
                    input.close();
                    }
                    private void displayDefaultImage() {
                 try {
                  image = Image.createImage("/res/logo.png");
              } catch (IOException ex) {
                 ex.printStackTrace();
                  }
                  }
                  }
ImageClass: it will return the image class reference


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.DataInputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Image;
/**
 *
 * @author welcome
 */
public class ImageClass {
    private RssMidlet parentMidlet;
    private DataInputStream is = null;
    private Image img = null;
    private Display display;
    public Image getImage(RssMidlet parentMidlet, String imageurl) {
        this.parentMidlet = parentMidlet;
        display = Display.getDisplay(parentMidlet);
        try {
            HttpConnection c = (HttpConnection) Connector.open(imageurl);
            int len = (int) c.getLength();
            if (len > 0) {
                is = c.openDataInputStream();
                byte[] data = new byte[len];
                is.readFully(data);
                img = Image.createImage(data, 0, len);
                //img=createThumbnail(img);
            } else {
                showAlert("length is null");
            }
            is.close();
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
            showAlert(e.getMessage());
        }
        return img;
        }
       private void showAlert(String err) {
        Alert a = new Alert("");
        a.setString(err);
        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a);
         }
         }


RssModel Class:

import javax.microedition.lcdui.Image;
public class RssModel {
    private String title;
    private Image image;
    public RssModel(String Title,Image image) {
        title = Title;
        this.image = image;
    }
    public String getTitle() {
        return title;
    }
   
    public Image getImage() {
        return image;
    }
 
    }