Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
Posts: 22
Registered: ‎03-14-2011
My Device: torch 9800
My Carrier: Developer

xml parser

hi,

I can parse a local XML file  (  private static String _xmlFileName = "/xml/index.xml";) but I want to parse an XML file not local (http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=scottgu)

 

 

 

 

this the code of XML_Parser (LOCAL)

 

 

/*
 * XMLDemoScreen.java
 *
 * Copyright © 1998-2010 Research In Motion Ltd.
 * 
 * Note: For the sake of simplicity, this sample application may not leverage
 * resource bundles and resource strings.  However, it is STRONGLY recommended
 * that application developers make use of the localization features available
 * within the BlackBerry development platform to ensure a seamless application
 * experience across a variety of languages and geographies.  For more information
 * on localizing your application, please refer to the BlackBerry Java Development
 * Environment Development Guide associated with this release.
 */


import java.io.InputStream;

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

import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * The main screen for the application.  Displays the results of parsing the XML file.
 */
public final class XMLDemoScreen extends MainScreen
{
    // Statics -------------------------------------------------------------------------------------
    private static String _xmlFileName = "/xml/index.xml";
    
    // Constants -----------------------------------------------------------------------------------
    private static final int _tab = 4;
    
    
    /**
     * This constructor parses the XML file into a W3C DOM document, and displays it 
     * on the screen.
     * 
     * @see Document
     * @see DocumentBuilder
     * @see DocumentBuilderFactory
     */
    public XMLDemoScreen() 
    {
        setTitle("XML Demo");
        
        try 
        {
            // Build a document based on the XML file.
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            
//            StreamConnection stream = (StreamConnection)Connector.open("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=scottgu");
//            InputStream inputStream=stream.openInputStream();
            
            InputStream inputStream = getClass().getResourceAsStream( _xmlFileName );
            Document document = builder.parse( inputStream );
            
            // Normalize the root element of the XML document.  This ensures that all Text 
            // nodes under the root node are put into a "normal" form, which means that 
            // there are neither adjacent Text nodes nor empty Text nodes in the document.
            // See Node.normalize().
            Element rootElement = document.getDocumentElement();
            rootElement.normalize();
            
            // Display the root node and all its descendant nodes, which covers the entire
            // document.
            displayNode( rootElement, 0 );
        } 
        catch ( Exception e ) 
        {
            System.out.println( e.toString() );
        }
    }
    
    
    /**
     * Displays a node at a specified depth, as well as all its descendants.
     * 
     * @param node The node to display.
     * @param depth The depth of this node in the document tree.
     */
    private void displayNode( Node node, int depth ) 
    {        
        // Because we can inspect the XML file, we know that it contains only XML elements
        // and text, so this algorithm is written specifically to handle these cases.  
        // A real-world application will be more robust, and will handle all node types. 
        // See the entire list in org.w3c.dom.Node.      
        // The XML file is laid out such that each Element node will either have one Text 
        // node child (e.g. <Element>Text</Element>), or >= 1 children consisting of at 
        // least one Element node, and possibly some Text nodes.  Start by figuring out
        // what kind of node we're dealing with.
        if ( node.getNodeType() == Node.ELEMENT_NODE ) 
        {
            StringBuffer buffer = new StringBuffer();
            indentStringBuffer( buffer, depth );
            NodeList childNodes = node.getChildNodes();
            int numChildren = childNodes.getLength();
            Node firstChild = childNodes.item( 0 );
            
            // If the node has only one child and that child is a Text node, then it's of 
            // the form  <Element>Text</Element>, so print 'Element = "Text"'.
            if ( numChildren == 1 && firstChild.getNodeType() == Node.TEXT_NODE ) 
            {
                buffer.append( node.getNodeName() ).append( " = \"" ).append( firstChild.getNodeValue() ).append( '"' );
                add( new RichTextField( buffer.toString() ) );
            } 
            else 
            {
                // The node either has > 1 children, or it has at least one Element node child. 
                // Either way, its children have to be visited.  Print the name of the element
                // and recurse.
                buffer.append( node.getNodeName() );
                add( new RichTextField( buffer.toString() ) );
                
                // Recursively visit all this node's children.
                for ( int i = 0; i < numChildren; ++i ) 
                {
                    displayNode( childNodes.item( i ), depth + 1 );
                }
            }
        } 
        else 
        {
            // Node is not an Element node, so we know it is a Text node.  Make sure it is 
            // not an "empty" Text node (normalize() doesn't consider a Text node consisting
            // of only newlines and spaces to be "empty").  If it is not empty, print it.
            String nodeValue = node.getNodeValue();
            if ( nodeValue.trim().length() != 0 ) 
            {
                StringBuffer buffer = new StringBuffer();
                indentStringBuffer( buffer, depth );
                buffer.append( '"' ).append( nodeValue ).append( '"' );
                add( new RichTextField( buffer.toString() ) );
            }
        }
    }
    
    
    /**
     * Adds leading spaces to the provided string buffer according to the depth of 
     * the node it represents.
     * 
     * @param buffer The string buffer to add leading spaces to.
     * @param depth The depth of the node the string buffer represents.
     */
    private static void indentStringBuffer( StringBuffer buffer, int depth ) 
    {
        int indent = depth * _tab;
        
        for ( int i = 0; i < indent; ++i ) 
        {
            buffer.append( ' ' );
        }
    }
}

 thx.

 

 

Developer
Posts: 16,786
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport
My Carrier: O2 Germany

Re: xml parser

use the inputstream of an httpconnection

----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Contributor
Posts: 22
Registered: ‎03-14-2011
My Device: torch 9800
My Carrier: Developer

Re: xml parser

[ Edited ]

i was remplace

 

// InputStream inputStream = getClass().getResourceAsStream( _xmlFileName );

 

 

with this code:

 

 HttpConnection stream = (HttpConnection)Connector.open("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=scottgu");
            InputStream inputStream=stream.openInputStream();

 

but it doesn't worked

 

Developer
Posts: 16,786
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport
My Carrier: O2 Germany

Re: xml parser

 

try to download the file normally first.

i use http://www.blackberry.com/developers/docs/6.0.0api/net/rim/device/api/io/IOUtilities.html#streamToBy...

 

you can remove it later, but to check your problem it is helpful.

don't forget to check the response code of the connection, too.

----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Developer
Posts: 19,631
Registered: ‎07-14-2008
My Device: Not Specified

Re: xml parser

I actually recommend that you download the entire file first before you start parsing anyway. 

Developer
Posts: 92
Registered: ‎02-22-2011
My Device: Not Specified

Re: xml parser

First of all, get your XML file from internet. I'm using some code like this one: 

 

 

public String getXml(String url){
		String xml = new String();
		try {
			StreamConnection s = null;
            s = (StreamConnection)Connector.open(url);
            HttpConnection httpConn = (HttpConnection)s; 
			
			int status = httpConn.getResponseCode();
			if (status == HttpConnection.HTTP_OK){
                InputStream input = s.openInputStream();

                byte[] data = new byte[256];
                int len = 0;
                int size = 0;
                StringBuffer raw = new StringBuffer();
                    
                while ( -1 != (len = input.read(data)) ){
                	raw.append(new String(data, 0, len));
                    size += len;    
                }
                xml = raw.toString();
                  
                input.close();
			}
		} catch (IOException e) {
			//Control de la excepcion de la conexion al servidor
			e.printStackTrace();
		}
		return xml;
	}

 

 

Also check out to Peter's internet conexion example

http://supportforums.blackberry.com/t5/Java-Development/Sample-HTTP-Connection-code-and-BIS-B-Access...

 

Hope it helps you out! Smiley Very Happy

Contributor
Posts: 22
Registered: ‎03-14-2011
My Device: torch 9800
My Carrier: Developer

Re: xml parser

please can someone help me

am I doing something wrong? I am very confused.

Here is my code:

 

package com.myapp.blackberry;

import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import java.util.Vector;

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

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

public class HomeScreen extends UiApplication {
    public static void main(String[] args)
    {
        HomeScreen theApp = new HomeScreen();
        theApp.enterEventDispatcher();
    }

    public HomeScreen()
    {
        pushScreen(new HomeNavigationScreen());
    }
}

class HomeNavigationScreen extends MainScreen
{
    private ListField navField;
    private Vector navItems;
    Connection _connectionthread;

    public HomeNavigationScreen()
    {

        setTitle("my app");

        navItems = new Vector();
        navField = new ListField();

        ListCallback callBack = new ListCallback();
        navField.setCallback(callBack);

        _connectionthread = new Connection();
        _connectionthread.start();


        add(navField);

    }

    private class ListCallback implements ListFieldCallback
    {
        public void drawListRow(ListField list, Graphics g, int index, int y, int w)
        {
            String text = (String) this.get(list, index);

            g.drawText(text, 0, y, 0, w);
        }

        public Object get(ListField listField, int index) {
            return navItems.elementAt(index);
        }

        public int getPreferredWidth(ListField listField) {
            return Display.getWidth();
        }

        public int indexOfList(ListField listField, String prefix, int start) {
            return navItems.indexOf(prefix, start);
        }
    }

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

        public void run(){
            // define variables later used for parsing
            Document doc;
            StreamConnection conn;
            try{
                conn = (StreamConnection)Connector.open("http://localhost/events.xml");
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                docBuilder.isValidating();
                doc = docBuilder.parse(conn.openInputStream());
                doc.getDocumentElement().normalize();
                NodeList list = doc.getElementsByTagName("Event");

                for (int i=0;i<list.getLength();i++){

                    Node currNode = list.item(i);

                    if (currNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element currElement = (Element) currNode;

                        NodeList titleList = currElement.getElementsByTagName("title");
                        Element titleElem = (Element) titleList.item(0);
                        NodeList titleNode = titleElem.getChildNodes();
                        String title = ((Node) titleNode.item(0)).getNodeValue();

                        navItems.addElement(title);
                        navField.insert(i);
                    }   
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

 

 

 

 

 

Developer
Posts: 19,631
Registered: ‎07-14-2008
My Device: Not Specified

Re: xml parser

localhost will not work, put a real IP or a real resolvable address in there.

 

I would strongly recommend that you check the response code before you start processing.

 

As already noted, I would also recommend that you down;load the entire XML before you start parsing.

 

Until you do this, you don't know where the problem is - it could be the parsing, or it could be the connection.   

 

I realize I am just repeating what has already been said.  But could you please do it?

Developer
Posts: 16,786
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport
My Carrier: O2 Germany

Re: xml parser

just to add to the "download first" suggestion:

a pullparser parses while downloading, it is more effective for larger xml sometimes as not the full xml has to be buffered in memory (depending on the structure, of course).

 

if something does not work you should download the full file first in any case.

you can also add an xml file as a resource to your project and parse this to test the parser part.

try to dismantle your processing into simple steps and execute them until one does not work to locate the problem.

----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Contributor
Posts: 22
Registered: ‎03-14-2011
My Device: torch 9800
My Carrier: Developer

Re: xml parser

thx for reply,

I already downloaded and I parsed the xml  and it worked well but my problem is in the connection