Monday, August 1, 2011

Parsing XML / RSS and displaying in List Field -- BlackBerry


Hi all. Here i have parsed xml values from a live RSS url using DOM parser and displayed in a List Field with a neat black background and separated lines.



CODE




package parsepack;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmlparsing extends UiApplication implements ListFieldCallback, FieldChangeListener
{

public static void main(String[] args)
{
xmlparsing app = new xmlparsing();
app.enterEventDispatcher();
}


public long mycolor ;
Connection _connectionthread;
private static ListField _list;
private static Vector listElements = new Vector();
public MainScreen screen = new MainScreen();
VerticalFieldManager mainManager;
VerticalFieldManager subManager;



public xmlparsing()
{
super();
pushScreen(screen);

final Bitmap backgroundBitmap = Bitmap.getBitmapResource("blackbackground.png");

mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
{

public void paint(Graphics graphics)
{
graphics.drawBitmap(0, 0, Display.getWidth(),Display.getHeight(),backgroundBitmap, 0, 0);

super.paint(graphics);
}

};

subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
{
protected void sublayout( int maxWidth, int maxHeight )
{
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();

super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};


screen.add(mainManager);

_list = new ListField()

{

public void paint(Graphics graphics)

{
graphics.setColor((int) mycolor);
super.paint(graphics);

}

};
mycolor = 0x00FFFFFF;
_list.invalidate();
_list.setEmptyString("* Feeds Not Available *", DrawStyle.HCENTER);
_list.setRowHeight(50);
_list.setCallback(this);
mainManager.add(subManager);
listElements.removeAllElements();
_connectionthread = new Connection();
_connectionthread.start();
}


protected boolean navigationClick(int status, int time)
{
try
{
//navigate here to another screen if you need.
}
catch(Exception e)
{
System.out.println("Exception:- : navigationClick() "+e.toString());
}
return true;
}



private class Connection extends Thread
{
public Connection()
{
super();
}

public void run() {
Document doc;
StreamConnection conn = null;
InputStream is = null;
try {

conn = (StreamConnection) Connector.open("http://timesofindia.feedsportal.com/c/33039/f/533917/index.rss"+";deviceside=true");

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilderFactory.setCoalescing(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
is = conn.openInputStream();
doc = docBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("title");
for (int i = 0; i < list.getLength(); i++) {
Node textNode = list.item(i).getFirstChild();
listElements.addElement(textNode.getNodeValue());
}

} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (is != null) {
try { is.close();
} catch (IOException ignored) {}
} if (conn != null) {
try { conn.close(); }
catch (IOException ignored) {}
} } UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(listElements.size());
subManager.add(_list);
screen.invalidate();
}
});
}

}


public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
String tes = (String)listElements.elementAt(index);
int yPos = 0+y;
g.drawLine(0, yPos, w, yPos);
g.drawText(tes, 5, 15+y, 0, w);
}


public Object get(ListField list, int index)
{
return listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
public void insert(String toInsert, int index) {
listElements.addElement(toInsert);
}

public void fieldChanged(Field field, int context) {


}
}



Download Full Project
Arun Kumar Munusamy Web Developer

Morbi aliquam fringilla nisl. Pellentesque eleifend condimentum tellus, vel vulputate tortor malesuada sit amet. Aliquam vel vestibulum metus. Aenean ut mi aucto.

4 comments:

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    html5 converter

    ReplyDelete
  2. thanks for sharing your knowledge. I have two questions? 1. suppose i want to go to a new screen when i click on a list. how do i do it in your code? I see you left a section for it but i am having problems.please help. i am a newbie.

    2. Suppose i want to collect more than one item within an xml file and want to store it in an array or node as you used. And then display all that information on another screen. what do i have to do?

    thanks. my email is ejobity@gmail.com

    ReplyDelete
  3. ok i fixed the first problem.

    i still would like help with the second problem if you have time.

    The problem i am having trying to edit your code is the i want to be able to store all the elements and display all the information or elements of that tag on another screen.

    I want to be able to click on an item on the list as you have it, and on another screen display all the information for the selected item in that list.

    Lets say i read from the xml file, and i display in a list all the "from", that would be Jani & Mace. when i select one of them, on the next screen it will display the rest of the information like "heading" & "info"

    ReplyDelete
  4. This code's giving a nullpointerexception in the run method of the Connection Class. How do I resolve it?

    ReplyDelete