Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

BlackBerry: Working with XML

$
0
0

XML is one of the most commonly used data-interchange formats on the web. With the proliferation of smartphones, it has become a common requirement to parse and display XML documents on mobile devices. In this article, I’ll teach you how to parse an XML document on BlackBerry and also display an XML document on BlackBerry.


Installing the BlackBerry Eclipse Plugin

First, we need to install the BlackBerry Java Plug-in for Eclipse, which may be installed with one of the following two methods.

  1. From the BlackBerry Java Plugin Update site
  2. From the plugin .exe file BlackBerry_JDE_PluginFull_1.5.0_helios.exe.

We shall discuss each of these methods in this section. To install from the update site, select Help>Install New Software in Eclipse Java IDE. In the Install window, click on Add underneath Available Software. In the Add Repository window, specify the Name as BlackBerry Java Plug-in Update Site and the Location as http://www.blackberry.com/go/eclipseUpdate/3.6/java as shown in the following illustration.



Specifying BlackBerry Plugin Update Site Location

The update website gets added to Available Software and the available software for the website gets listed including the different versions. Select BlackBerry Java Plug-in Category Version 7.0.0.28. Click on Next.



Selecting Software to Install

In the Install Details section, the BlackBerry Java SD 7.0.0.28 gets listed. Click on Next.



BlackBerry Plugin Install Details

Accept the license agreement and click on Finish. The Installing Software dialog gets displayed. After the software gets installed a dialog to indicate the Restart requirement gets displayed. Click on Restart Now. The BlackBerry Java Plug-in for Eclipse gets installed.

In the second method, click on the BlackBerry_JDE_PluginFull_1.5.0_helios.exe or an earlier version exe file. The BlackBerry Java Plug-in for Eclipse wizard gets started. Click on Next in Introduction.



The BlackBerry Java Plug-in for Eclipse wizard

Accept the license terms and click on Next. In Choose Installation Folder specify the directory in which to install the plugin, including the Eclipse IDE. Click on Next.



Selecting Installation Folder

In Select Additional Tasks select the default shortcut tasks and click on Next. In Pre-Installation Summary click on Install.



Installing BlackBerry Plugin

The BlackBerry Java Plug-in for Eclipse gets installed. Click on Done. Next, we need to open the BlackBerry perspective. Select Window>Open Perspective>Other. In Open Perspective, select BlackBerry Application Development and click on OK.


Opening the BlackBerry Application Development Perspective

Creating a BlackBerry Project

In this section we shall create a BlackBerry project in Eclipse using the BlackBerry Application Development perspective features. Select File>New. In New window select BlackBerry>BlackBerry Project and click on Next.



Creating a BlackBerry Project

In the New BlackBerry Project window, specify Project Name (ParsingXML for example). Select JRE as BlackBerry JRE 7.0.0. Click on Next.



Specifying BlackBerry Project Name

In Java Settings select the default build settings, which include src and res folders for project source code and the bin folder for the output. Click on Next.



Specifying BlackBerry Project Java Settings

In the Templates section, select the BlackBerry Application template and click on Next.



Selecting Project Template

In the UI Application window, specify the Application Details. Specify a Package Name (blackberry.xml), Application Class Name (ParsingXML), Screen Class Name (Parsing_XML), and a Screen Title. Click on Finish.



Specifying Application Details

A BlackBerry Project gets created. The BlackBerry project consists of the following
artifacts:

  1. A class (ParsingXML) that extends the UiApplication class.
  2. A class (Parsing_XML) that extends the MainScreen class.
  3. A BlackBerry application descriptor file BlackBerry_App_Descriptor.xml.

The directory structure of the BlackBerry project is shown below.



BlackBerry Project Structure

Configuring the BlackBerry Descriptor

The properties of a BlackBerry project are specified in the BlackBerry_App_Descriptor.xml file, shown below in GUI mode.



BlackBerry_App_Descriptor.xml file

The General Information includes the following property fields/checkboxes.

FieldDescriptionValue
TitleThe application titleParsing XML
VersionThe application version1.0.0
VendorThe vendor nameBlackBerry Developer
Application Type“BlackBerry Application” for a BlackBerry applicationBlackBerry Application
BlackBerry ApplicationRuntime arguments to the application
Auto-run on StartupSelect checkbox to auto-run application on startuptrue
Startup TierThe startup priority7 (default) is the lowest priority
Do not display the application iconSelect checkbox to not display application icon

The Application Descriptor may also include Locale Resources and Application Icons. Alternate entry points may be used to run an application in background or foreground. The BlackBerry_App_Descriptor.xml is listed below.

<!-- This file has been generated by the BlackBerry Plugin for Eclipse v3.6.0. -->
<Properties ModelVersion="1.1.2">
  <General Title="Parsing XML" Version="1.0.0" Vendor="BlackBerry Developer" Description=""/>
  <Application Type="BlackBerry Application" MainMIDletName="" MainArgs="" HomeScreenPosition="0" StartupTier="7" IsSystemModule="false" IsAutostartup="true"/>
  <Resources hasTitleResource="false" TitleResourceBundleName="" TitleResourceBundleRelativePath="" TitleResourceBundleClassName="" TitleResourceBundleKey="" DescriptionId="">
    <Icons>
      <Icon CanonicalFileName="res\img\icon.png" IsFocus="false"/>
    </Icons>
  </Resources>
  <KeywordResources KeywordResourceBundleName="" KeywordResourceBundleRelativePath="" KeywordResourceBundleClassName="" KeywordResourceBundleKey=""/>
  <Compile OutputCompilerMessages="false" ConvertImages="true" CreateWarningForNoExportedRoutine="true" CompressResources="false" AliasList="">
    <PreprocessorDefines/>
  </Compile>
  <Packaging PreBuildStep="" PostBuildStep="" CleanStep="" OutputFileName="ParsingXML" OutputFolder="deliverables" GenerateALXFile="true">
    <AlxFiles/>
  </Packaging>
  <HiddenProperties>
    <ClassProtection/>
    <PackageProtection/></HiddenProperties>
  <AlternateEntryPoints/>
</Properties>

Creating the Screen class

In this section we shall create a screen for the BlackBerry application. At the minimum a screen should have a title. A screen is a MainScreen class and provides features common to RIM device applications. Create a class that extends the MainScreen class and in the class constructor set the screen title using the setTitle method. The screen class Parsing_XML is listed below.

package blackberry.xml;
import net.rim.device.api.ui.container.MainScreen;
/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class Parsing_XML extends MainScreen
{
    /**
     * Creates a new Parsing_XML object
     */
    public Parsing_XML()
    {
        // Set the displayed title of the screen
        setTitle("Parsing XML");
    }
}

Parsing an XML Document

In the ParsingXML class we shall parse an XML document. The catalog.xml document has a catalog for a journal.

<?xml version = '1.0' encoding = 'UTF-8'?>
<catalog journal="Oracle Magazine" publisher="Oracle Publishing">
    <article>
        <edition>Sept-Oct 2005</edition>
        <title>Creating Search Pages</title>
        <author>Steve Muench</author>
    </article>
    <article>
        <edition>November - December 2010</edition>
        <title>Agile Enterprise Architecture</title>
        <author>Bob Rhubart</author>
    </article>
</catalog>

Copy the XML document to the res folder in the src folder, or directly in the src folder. Next, we shall develop the ParsingXML class, which extends the UiApplication class, the base class for all device applications that provide a user interface. Create an instance variable for the MainScreen. Create a String variable for element values. We shall use a Thread to parse the XML document. Create an instance variable for the thread class.

Parsing_XML screen = new Parsing_XML();
String element;
Connection connection;

In the class constructor set the screen title, and add the MainScreen screen onto the UI stack for rendering. Create a Thread instance and start the thread with the start() method.

screen.setTitle("Parsing XML");
pushScreen(screen);
connection = new Connection();
connection.start();

In the main method, create an instance of the ParsingXML class and invoke the event dispatcher thread using the enterEventDispatcher method.

All BlackBerry framework UI applications contain one event dispatcher thread. After a screen has been pushed onto the display stack all modifications must be made either on the event dispatcher thread or a background thread. We shall use a background thread Connection to parse the XML document catalog.xml.

ParsingXML theApp = new ParsingXML();
theApp.enterEventDispatcher();

Create a DocumentBuilderFactory factory instance using static method newInstance() to create a DOM parser from and subsequently create a DOM tree from the XML document.

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

Create a DocumentBuilder parser instance using the newDocumentBuilder method to subsequently parse the XML document and create a DOM document object.

DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

Set the parser to be validating using the isValidating() method.

docBuilder.isValidating();

Create an InputStream object from the catalog.xml document. Include the ‘/’ in the catalog.xml path.

InputStream inputStream = getClass().getResourceAsStream("/catalog.xml");

Alternatively, the InputStream may be created using a String literal for the XML, and a ByteArrayInputStream.

/**   str = "<?xml version = '1.0' encoding = 'UTF-8'?>" +
                  "<catalog journal='Oracle Magazine' publisher='Oracle Publishing'>"
                  + "<article>" + "<edition>Sept-Oct 2005</edition>"+
                  "<title>Creating Search Pages</title>"+
                  "<author>Steve Muench</author>" + "</article>" + "<article>"
                  + "<edition>November - December 2010</edition>" +
                  "<title>Agile Enterprise Architecture</title>"+
                  "<author>Bob Rhubart</author>"+ "</article>"+ "</catalog>";
                // convert String into InputStream
InputStream inputStream =new ByteArrayInputStream(str.getBytes());**

Next, obtain a DOM Document object from the InputStream using the parse(InputStream) method.

Document document = docBuilder.parse(inputStream);

Get the Document element, which is the child node of the XML document, also the root element, using the getDocumentElement() method. Normalize the XML document using the normalize() method, which removes adjacent and empty Text nodes.

document.getDocumentElement().normalize();

We shall output the <title> element values to the screen. Create a NodeList of the title elements using the getElementsByTagName() method.

NodeList list = document.getElementsByTagName("title");

The first child node of an element is the text node in the element. The text value in a Text node is obtained using the getNodeValue() method. Iterate over the NodeList and obtain the text node values for the title elements. To display the title values on the screen first, we need to obtain the event lock using the getEventLock() method.

synchronized (UiApplication.getEventLock()) {
}

The event lock is required for performance and concurrency issues. Output the title values to the screen using the add() method.

screen.add(new RichTextField("Title : " + element));
screen.add(new SeparatorField());

If using the String literal for the XML document output the String to the screen.

screen.add(new RichTextField(str));

In the catch block output exception message if any.

screen.add(new RichTextField("Error : " + e.toString()));

The ParsingXML.java class is listed below.

package blackberry.xml;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.microedition.io.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class ParsingXML extends UiApplication {
    // creating a member variable for the MainScreen
    Parsing_XML screen = new Parsing_XML();
    // string variable to store the value of the XML document element/s
    String element;
    Connection connection;
    public static void main(String arg[]) {
        ParsingXML theApp = new ParsingXML();
        theApp.enterEventDispatcher();
    }
    public ParsingXML() {
        screen.setTitle("Parsing XML");// setting title
        screen.add(new RichTextField("Requesting Catalog titles....."));
        screen.add(new SeparatorField());
        // Push a screen onto the UI stack for rendering.
        pushScreen(screen);
        connection = new Connection();
        connection.start();//
    }
    private class Connection extends Thread {
        public Connection() {
            super();
        }
        public void run() {
            StreamConnection conn;
            String str=null;
            try {
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder docBuilder = docBuilderFactory
                        .newDocumentBuilder();
                docBuilder.isValidating();
                InputStream inputStream = getClass().getResourceAsStream("/catalog.xml");
                /**   str = "<?xml version = '1.0' encoding = 'UTF-8'?>" +
                  "<catalog journal='Oracle Magazine' publisher='Oracle Publishing'>"
                  + "<article>" + "<edition>Sept-Oct 2005</edition>"+
                  "<title>Creating Search Pages</title>"+
                  "<author>Steve Muench</author>" + "</article>" + "<article>"
                  + "<edition>November - December 2010</edition>" +
                  "<title>Agile Enterprise Architecture</title>"+
                  "<author>Bob Rhubart</author>"+ "</article>"+ "</catalog>";
                // convert String into InputStream
                  InputStream inputStream =new ByteArrayInputStream(str.getBytes());**/
                Document document = docBuilder.parse(inputStream);
                document.getDocumentElement().normalize();
                NodeList list = document.getElementsByTagName("title");
                element = new String();
                // this "for" loop is used to parse through the
                // XML document and extract all elements and their
                // value, so they can be displayed on the device
                for (int i = 0; i < list.getLength(); i++) {
                    Node value = list.item(i).getChildNodes().item(0);
                    element = value.getNodeValue();
                    synchronized (UiApplication.getEventLock()) {
                        screen.add(new RichTextField("Title : " + element));
                        screen.add(new SeparatorField());
                    }
                }// end for
                                          //      screen.add(new RichTextField(str));
            }// end try
                // will catch any exception thrown by the XML parser
            catch (Exception e) {
                screen.add(new RichTextField("Error : " + e.toString()));
            }
        }// end connection function
    }// end connection class
}

Running the BlackBerry Project

Next, we shall run the ParsingXML application in Eclipse IDE. Right-click on ParsingXML and select Run As>BlackBerry Simulator.



Running BlackBerry Application

The BlackBerry Simulator gets started. The application gets installed on the BlackBerry Simulator.



Installed BlackBerry Application

Click on the application to run the application.



Running BlackBerry Application

The titles from the catalog.xml document get displayed.



Parsing XML Document

The directory structure of the ParsingXML application is shown below.



Directory Structure of ParsingXML Application

If the XML document is created from a String literal, the XML may be output to the screen as well.



Displaying XML Document



Summary

In this article we learned about parsing XML on a BlackBerry using the BlackBerry JDE. We used the BlackBerry Java Plug-in for Eclipse to add the BlackBerry Application Development perspective to Eclipse IDE. We used the MainScreen class to create a screen for BlackBerry device. We used the UiApplication class to create an event dispatcher thread, which a BlackBerry framework application is required to have. We created a background thread to parse an XML document and obtained an event lock to display the parsed catalog titles on the BlackBerry screen. We also output the XML document to the screen.


Viewing all articles
Browse latest Browse all 1836

Trending Articles