I found one sample application from the Blackberry knowledgebase.
From that application I have put that sample application on my eclipse plugin, and the code is as follows :
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.*;
class XML_Parsing_Sample extends UiApplication {
// creating a member variable for the MainScreen
MainScreen _screen = new MainScreen();
// string variables to store the values of the XML document
String _node, _element;
Connection _connectionthread;
public static void main(String arg[]) {
XML_Parsing_Sample application = new XML_Parsing_Sample();
// create a new instance of the application
// and start the application on the event thread
application.enterEventDispatcher();
}
public XML_Parsing_Sample() {
_screen.setTitle("XML Parsing");// setting title
_screen.add(new RichTextField("Requesting....."));
_screen.add(new SeparatorField());
pushScreen(_screen); // creating a screen
// creating a connection thread to run in the background
_connectionthread = new Connection();
_connectionthread.start();// starting the thread operation
}
public void updateField(String node, String element) {
// receiving the parsed node and its value from the thread
// and updating it here
// so it can be displayed on the screen
String title = "My App";
_screen.add(new RichTextField(node + " : " + element));
if (node.equals(title)) {
_screen.add(new SeparatorField());
}
}
private class Connection extends Thread {
public Connection() {
super();
}
public void run() {
// define variables later used for parsing
Document doc;
StreamConnection conn;
try {
// providing the location of the XML file,
// your address might be different
conn = (StreamConnection) Connector
.open("http://www.sufalamtech.com/demo/moviewebservice/Test.xml");
// next few lines creates variables to open a
// stream, parse it, collect XML data and
// extract the data which is required.
// In this case they are elements,
// node and the values of an element
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory
.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(conn.openInputStream());
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_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);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
updateField(_node, _element);
}// end for
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Dialog.alert("exception = " + e);
}
}// end connection function
}// end connection class
}// end XML_Parsing_Sample
But when I am running this application, the simulator just showing me a Blank screen with label Requesting...
Anybody help me out for this ?
Thanks in advance...
Try this
public void updateField(String node, String element) {
// receiving the parsed node and its value from the thread
// and updating it here
// so it can be displayed on the screen
//Don't forget to add this next line when called from a thread
synchronized (UiApplication.getEventLock()) {
String title = "My App";
_screen.add(new RichTextField(node + " : " + element));
if (node.equals(title)) {
_screen.add(new SeparatorField());
}
}
}
This synchronized (UiApplication.getEventLock()) is really important, you need this every time thread try to access the UI.
More solutions exist, see the documentation
Related
My program uses Picocli to parse XML data and store it in an ArrayList. For some reason, the information gets removed when I try to access it from another class.
I run the code below, and it shows the elements just fine:
public class SourceSentences {
static String source;
static ArrayList<String> sourceArray = new ArrayList<>();
public static void translate() throws ParserConfigurationException, IOException, SAXException {
String xmlFileLocation = "C:\\Users\\user\\Desktop\\exercise\\source.txml";
System.out.println("---------------");
System.out.println("Get Text From Source File: ");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
//parse '.txml' file
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new File(xmlFileLocation));
//...
document.getDocumentElement().normalize();
//specify tag in the '.txml' file and iterate
NodeList nodeList = document.getElementsByTagName("segment");
for (int i = 0; i < nodeList.getLength(); i++) {
//this is tag index of where line of el are
Node node = nodeList.item(i);
//check if actually a node
if (node.getNodeType() == Node.ELEMENT_NODE) {
//create a node object that will retrieve the element in the XML file
Element element = (Element) node;
//get the element from the specified node in nodeList
source = element.getElementsByTagName("source").item(0).getTextContent();
//check what it looks like
System.out.println(source);
//add to arraylist
sourceArray.add(source);
}
/*String[] arr = source.split("\\s");
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr));*/
}
//get its data type to make sure
System.out.println("data type: " + source.getClass().getSimpleName());
System.out.println(sourceArray);
}
}
So I try to access sourceArray from another class:
class getArrayElements extends SourceSentences{
public static void main(String[] args) {
System.out.println(SourceSentences.sourceArray);
}
}
and results in variables being [], thus not able to transfer data to another class.
Picocli setup snippet:
public class TranslateTXML implements Callable<String> {
#Option(names = "-f", description = " path to source txml file")
private String file;
#Option(names = "-o", description = "output path")
private String output;
public static void main(String... args) throws Exception {
int exitCode = new picocli.CommandLine(new TranslateTXML()).execute(args);
System.exit(exitCode);
}
public String call() throws Exception {
if (file != null) {
if (file.equals("C:\\Users\\gnier\\Desktop\\exercise\\source.txml")) {
sourceSent("C:\\Users\\gnier\\Desktop\\exercise\\source.txml");
System.out.println("source.txml data retrieved\n");
} else {
System.out.println("File \"source.txml\" not found. Check FileName and Directory.");
System.exit(2);
}
}
WriteSourceTranslatedToTXML.makeTranslated(System.out);
System.out.println("translated made");
System.out.println("------");
System.out.println("File \"translated.txml\" has been outputted to designated path");
}
}
The static context of the SourceSentences.main() is lost once you run the getArrayElements.main() method. The parsing of your XML data never happened as far as getArrayElements.main() was concerned.
You need to call the translate method from inside the getArrayElements' main function.
class getArrayElements extends SourceSentences {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
SourceSentences.translate();
System.out.println(SourceSentences.sourceArray);
}
}
I've been working on a tool to convert data into the Collada .DAE format, which is XML based. Unfortunately, one thing has been stopping me: My exported XML doesn't have any of my elements!
Here's the code. I've made it easy-to-read so that you don't have to go through as much of the trouble of reading it.
public class DAEExport {
private static boolean alreadyConstructed = false;
private static Document doc = null;
private static Element root = null;
private static Element lib_images_base_element = null;
private static Element lib_geometry_base_element = null;
private static Element lib_control_base_element = null;
private static Element lib_visual_scene_base_element = null;
public static void AppendData() {
//Normally this method would have the data to append as its args, but I'm not worried about that right now.
//Furthermore, ASSUME THIS RUNS ONLY ONCE (It runs once in the test code I'm using to run this method)! I know that it won't work if called multiple times, as the below variables for the document builder and such wouldn't exist the second time around
try {
if (!alreadyConstructed) {
alreadyConstructed = true;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("SomeGenericElement");
rootElement.appendChild(document.createTextNode("Generic test contents");
document.appendChild(rootElement);
doc = document;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Build(File _out) {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
alreadyConstructed = false;
doc = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ok so here's my problem: Despite adding those elements to the document by calling AppendData(), then calling Build() to print the data, I only get the following data:
<?xml version="1.0" encoding="UTF-8"?> - No elements. Just the basic header. This is it.
I don't know if it's because of some silly mistake that I've been oblivious to for the past amount of time, or something else. Any answers as to why my elements disappeared?
Currently, your doc object is not being passed from AppendData() method to Build() method. All Build() uses is an empty doc from declaration: doc = null. Hence, your outcome is empty of nodes (TransformFactory adds the XML header).
Consider returning the doc object from AppendData() to be available at class level for other method (do note you change the void to returned object type). You then redefine doc and pass it into Build():
public static Document AppendData() {
...
doc = document
return(doc)
}
Alternatively, call Build() inside AppendData, passing doc as a parameter:
public static void AppendData() {
...
doc = document
Build(doc, outfile)
}
public static void Build(Document doc, File _out) {
...
}
Have spent hours trying to figure out why the "finalURL" variable in the "fetch" method cannot be read by the "Downloader" class? Would really appreciate any pointers..
It's a vocabulary improvement application, so it fetches XML data from a dictionary api.
public class DefineWord extends Activity {
static final String head = new String("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/");
static final String apikey = new String("?key=xxxxxx-xxx-xxx-xxxx-xxxxx");
TextView src;
EditText searchBar;
OnCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.defineword);
src=(TextView)findViewById(R.id.textFromWeb);
searchBar = (EditText)findViewById(R.id.searchBar);
}
fetch method:
public void fetch(View v){ //onClick in xml starts this "fetch" method
String w = searchBar.getText().toString(); // get the text the user enters into searchbar
String finalURL = head.trim() + w.trim() + apikey.trim(); //concatenate api url
Downloader d = new Downloader();
d.execute(finalURL); // Calls AsyncTask to connect in the background.
}
AsyncTask:
class Downloader extends AsyncTask<String,Void,String>{
ArrayList<String> information = new ArrayList<String>(); // Store fetched XML data in ArrayList
public String doInBackground(String... urls) {
String result = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
The problem is here. "finalURL" cannot be resolved to a variable.
Document doc = builder.parse(finalURL); //finalURL cannot be resolved to a variable ???
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("entry"); // Make a list of all elements in XML file with tag name "entry"
for (int temp = 0; temp < nList.getLength(); temp++) { //Iterate over elements and get their attributes (Definition, etymology...)
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
String element = ("\nCurrent Element : " + eElement.getAttribute("id"));
information.add(element); //
String definitions = ("\nDefinition : \n" + eElement.getElementsByTagName("dt").item(0).getTextContent());
information.add(definitions);
}
}
}catch (ParserConfigurationException e){
e.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return result;
}
protected void onPostExecute (String result){
String finalresult = information.toString();
src.setText(finalresult);
}
}
}
Thanks for your time.
This is called a parameter. By using asyncTask.execute(parameter) you pass in the objects to doInBackground(String... arrayOfParameters).
So to access the value again, you should use builder.parse(urls[0]);
finalURL is declared inside the fetch method and therefore can only be accessed within this function.
If you want it to be accessible throughout the program declare it outside of the function like so.
class MyClass{
public static String finalURL; // variable declaration
public void fetch(View v){
finalURL = head.trim() + w.trim() + apikey.trim(); // variable assignment
}
public void otherFunction(){
Document doc = builder.parse(finalURL); // retrieves static class variable
}
}
I hope this answers your question. If not, let me know what the confusion is.
I'm trying to make an application that displays news feed from a website so I get the input stream and parse it in document using SAX but it returns SAX exception that it is unable to determine type of coding of this Stream . I tried before that to put The website's stream manually in XML file and read the file and It worked but when streaming directly from Internet it throws that exception and this is my code :
public final class MyScreen extends MainScreen {
protected static RichTextField RTF = new RichTextField("Plz Wait . . . ",
Field.FIELD_BOTTOM);
public MyScreen() {
// Set the displayed title of the screen
super(Manager.NO_VERTICAL_SCROLL);
setTitle("Yalla Kora");
Runnable R = new Runnable();
R.start();
add(RTF);
}
private class Runnable extends Thread {
public Runnable() {
// TODO Auto-generated constructor stub
ConnectionFactory factory = new ConnectionFactory();
ConnectionDescriptor descriptor = factory
.getConnection("http://www.yallakora.com/arabic/rss.aspx?id=0");
HttpConnection httpConnection;
httpConnection = (HttpConnection) descriptor.getConnection();// Connector.open("http://www.yallakora.com/pictures/main//2011/11/El-Masry-807-11-2011-21-56-7.jpg");
Manager mainManager = getMainManager();
RichList RL = new RichList(mainManager, true, 2, 1);
InputStream input;
try {
input = httpConnection.openInputStream();
Document document;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
try {
document = docBuilder.parse(input);
document.getDocumentElement().normalize();
NodeList item = document.getElementsByTagName("item");
int k = item.getLength();
for (int i = 0; i < k; i++) {
Node value = item.item(i);
NodeList Data = value.getChildNodes();
Node title = Data.item(0);
Node link = Data.item(1);
Node date = Data.item(2);
Node discription = Data.item(5);
Node Discription = discription.getFirstChild();
String s = Discription.getNodeValue();
int mm = s.indexOf("'><BR>");
int max = s.length();
String imagelink = s.substring(0, mm);
String Khabar = s.substring(mm + 6, max);
String Date = date.getFirstChild().getNodeValue();
String Title = title.getFirstChild().getNodeValue();
String Link = link.getFirstChild().getNodeValue();
ConnectionFactory factory1 = new ConnectionFactory();
ConnectionDescriptor descriptor1 = factory1
.getConnection(imagelink);
HttpConnection httpConnection1;
httpConnection1 = (HttpConnection) descriptor1
.getConnection();
InputStream input1;
input1 = httpConnection1.openInputStream();
byte[] bytes = IOUtilities.streamToBytes(input1);
Bitmap bitmap = Bitmap.createBitmapFromBytes(bytes,
0, -1, 1);
;
RL.add(new Object[] { bitmap, Title, Khabar, Date });
add(new RichTextField(link.getNodeValue(),
Field.NON_FOCUSABLE));
}
RTF.setText("");
} catch (SAXException e) {
// TODO Auto-generated catch block
RTF.setText("SAXException " + e.toString());
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
RTF.setText("ParserConfigurationException " + e.toString());
e.printStackTrace();
}
} catch (IOException e) {
RTF.setText("IOException " + e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}
Any Ideas ??
I recommend restructuring this code into at least two parts.
I would create a download function that is given a URL and downloads the bytes associated with that URL. This should open and close the connection, and just return either the bytes downloaded or an error indication.
I would use this download processing as a 'function call' to download your XML bytes. Then parse the bytes that are obtained feeding these direct into your parser. If the data is properly constructed XML, it will have a header indicating the encoding used, so you do not need to worry about that, the parser will cope.
Once you have this parsed, then use the download function again to download the bytes associated with any images you want.
Regarding the SAX processing, have you reviewed this question:
parse-xml-inputstream-in-blackberry-java-application
I'm modifying an app that loads data dynamically from an XML file that contains a quiz and displays questions and replies. The change consists in the fact that i want to load a single(hardcoded for now) file instead of using a JFileChooser.
Here's the relevant code working before(undefined variables are class attributes but i won't post the whole class declaration):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i < nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
And now for the code that doesn't work:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:\\file.xml");
pathname = "C:\\file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
Also, the exception:
Exception in thread "main" java.lang.NullPointerException
and it occurs at question.setText(e.getAttribute("value")); on calling setupQuestion("q1");.
Edit: Interestingly enough System.out.println(fileName); gets printed before the Exception is thrown and System.out.println(idno); is printed after it. Actually on restarting the IDE both echos appear after the exception is thrown.
I've been stuck on this for quite some time. Any help is much appreciated.
Found the culprit. I guess I haven't mentioned everything. I've forgot to allocate memory for question and replies. I am so ashamed.