I am able to successfully run the Embeddedjava program.but my nodes are not getting reflected when i open the neo4j interface through localhost.For your reference
I made the following changes to my neo4j-server.properties
org.neo4j.server.database.location=C:/neo4j-community-1.9.6/data/graph.db/
org.neo4j.server.webadmin.data.uri=C:/neo4j-community-1.9.6/data/graph.db/
this is the same DB_path that i am using in the code.
Everytime I run the program ,the count on the dashboard increases by 2(i have created 2 nodes in my program).But when i run the query
START root=node(*)
return count(root)
it gives me the answer as 0.
Also,i noticed that the data/keystore file does not get generated when i run the java program.it gets generated only when i start the interface through localhost:7474.Does this have anything to do ?
Java Code
import java.io.File;
import java.io.IOException;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import org.neo4j.kernel.StoreLocker;
public class EmbeddedNeo4j
{
private static final String DB_PATH = "C://neo4j-community-1.9.6//data//graph.db";
public String greeting;
// START SNIPPET: vars
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
// END SNIPPET: vars
// START SNIPPET: createReltype
private static enum RelTypes implements RelationshipType
{
KNOWS
}
// END SNIPPET: createReltype
public static void main( final String[] args )
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb()
{
// clearDb();
// START SNIPPET: startDb
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
// registerShutdownHook( graphDb );
// END SNIPPET: startDb
// START SNIPPET: transaction
Transaction tx=null;
try
{
tx= graphDb.beginTx();
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
// END SNIPPET: addData
// START SNIPPET: readData
System.out.print( firstNode.getProperty( "message" ) );
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
// END SNIPPET: readData
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) );
tx.success();
}
catch(Exception e)
{
tx.failure();
}
finally
{
// Database operations go here
// END SNIPPET: transaction
// START SNIPPET: addData
// START SNIPPET: transaction
tx.finish();
}
// END SNIPPET: transaction
}
private void clearDb()
{
try
{
FileUtils.deleteRecursively( new File(DB_PATH) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
void removeData()
{
Transaction tx=null;
try
{
tx = graphDb.beginTx() ;
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
tx.success();
}
catch(Exception e)
{
tx.failure();
}
finally
{
// START SNIPPET: removingData
// let's remove the data
// END SNIPPET: removingData
tx.finish();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
// START SNIPPET: shutdownServer
graphDb.shutdown();
// END SNIPPET: shutdownServer
}
// START SNIPPET: shutdownHook
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
// END SNIPPET: shutdownHook
}
public static void main( final String[] args )
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
You are creating DB then calling removeData.
If your question is about the webadmin showing you an increase of 2 nodes when the query to count all nodes shows 0, then you should ignore the webadmin node count. It is not truly the number of nodes but sort of the highest node ID in use. The query
START root=node(*)
return count(root)
will correctly show you the number of nodes. This is 0 which is expected since your java program creates nodes and then deletes them.
Related
Maybe the title itself is enough to express my confusion. In one hand I read a lot that using transaction functions is the recommended way to use the neo4j java driver.
See Neo4j Java Driver
On the other hand, I see examples of codes, such as in Neo4j Java Driver 1.7 API where there is no transaction (or maybe it's implicit), and I like the idea of having a StatementResult and iterating on it.
So what should I do ?
Is there a way of having the iterator of an auto-commit transation in a transaction function ? Should I keep using the execute() function, the session.writeTransaction() function ?
It seems to me that there is a lot of way of running a simple request, but it can't figure why, or if theses methods can be a bit mixed up.
I'm not very happy with writeTransaction if I can only get a String out of it.
There is also the GitHub examples for this driver, especially the ResultRetain with the 'Record' object which is closer of what I'm looking for but without any iterator. It allows data to be extracted with accessers. Another close example is the ResultConsume but still no iterator.
Based on these examples I wrote the following code, it works as expected, with generator and getters.
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
public class InitializeUser extends Logger{
StatementResult result;
public void getUserForInitialization(){
try ( Session session = driver.session() )
{
result = session.readTransaction( new TransactionWork<StatementResult>()
{
#Override
public StatementResult execute( Transaction tx )
{
return tx.run(
"MATCH (a{initialized:false}) "+
"RETURN a.username as username");
}
} );
}
}
public void readGenerator(){
while (result.hasNext())
{
Record record = result.next();
System.out.println(record.get("username").asString());
}
}
}
I'm not sure if it's worse or better than following the ResultRetain or the ResultConsume example but it has a generator, getters and what I think is transaction functions. I'm still very open to suggestions and explanations.
If someone could explain a bit the mechanic behind TransactionWork(), execute(), and what is the difference between readTransaction(), writeTransaction(), run() and beginTransaction(), I would be delighted.
Neo4j Java Driver
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
#Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
#Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
Neo4j Java Driver 1.7 API
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample
{
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
try (Transaction tx = session.beginTransaction())
{
tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
private void printPeople(String initial)
{
try (Session session = driver.session())
{
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
// Values can be extracted from a record by index or name.
System.out.println(record.get("name").asString());
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
example.addPerson("Ada");
example.addPerson("Alice");
example.addPerson("Bob");
example.printPeople("A");
example.close();
}
}
Neo4j Java Driver ResultRetainExample
import java.util.List;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import[]
public class ResultRetainExample extends BaseApplication
{
public ResultRetainExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-retain[]
public int addEmployees( final String companyName )
{
try ( Session session = driver.session() )
{
int employees = 0;
List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
{
#Override
public List<Record> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
for ( final Record person : persons )
{
employees += session.writeTransaction( new TransactionWork<Integer>()
{
#Override
public Integer execute( Transaction tx )
{
tx.run( "MATCH (emp:Person {name: $person_name}) " +
"MERGE (com:Company {name: $company_name}) " +
"MERGE (emp)-[:WORKS_FOR]->(com)",
parameters( "person_name", person.get( "name" ).asString(), "company_name",
companyName ) );
return 1;
}
} );
}
return employees;
}
}
private static List<Record> matchPersonNodes( Transaction tx )
{
return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
}
// end::result-retain[]
}
Neo4j Java Driver ResultConsumeExample
import java.util.ArrayList;
import java.util.List;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
// end::result-consume-import[]
public class ResultConsumeExample extends BaseApplication
{
public ResultConsumeExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-consume[]
public List<String> getPeople()
{
try ( Session session = driver.session() )
{
return session.readTransaction( new TransactionWork<List<String>>()
{
#Override
public List<String> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
}
}
private static List<String> matchPersonNodes( Transaction tx )
{
List<String> names = new ArrayList<>();
StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
while ( result.hasNext() )
{
names.add( result.next().get( 0 ).asString() );
}
return names;
}
// end::result-consume[]
}
I am working on connecting Neo4j with Java via Eclipse, when I run the code it works and I got the nodes and their relationship between them, now I need to have a cypher query, I tried many ways but they did not work?
I have looked to this, but I had an error.
[EDITED]
Here is my code:
package testtest;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class Testnn {
// This is the path of the Neo4J
private static final String Neo4J_DBPath = "/Users/nahla.INTRA/Documents/Neo4j/default.graphdb";
Node first;
Node second;
Relationship relation;
GraphDatabaseService graphDataService;
// List of Relationships first knows second
private static enum RelTypes implements RelationshipType
{
KNOWS
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Testnn hello = new Testnn();
hello.createDatabase();
hello.removeData();
hello.shutDown();
}
void createDatabase ()
{
// GraphDatabaseService
graphDataService = new GraphDatabaseFactory().newEmbeddedDatabase(Neo4J_DBPath);
//Begin Transaction
Transaction transaction = graphDataService.beginTx();
try{
// create nodes and set the properties
first = graphDataService.createNode();
first.setProperty("name", "Tom");
second = graphDataService.createNode();
second.setProperty("name", "Sara");
// Relationship
relation = first.createRelationshipTo(second, RelTypes.KNOWS);
relation.setProperty("relationship-type", "KNOWS");
System.out.println(first.getProperty("name").toString());
System.out.println(relation.getProperty("relationship-type").toString());
System.out.println(second.getProperty("name").toString());
// success Transaction
transaction.success();
}
finally {
//finish the Transaction
transaction.finish();
}
}
void removeData ()
{
Transaction transaction = graphDataService.beginTx();
try
{
// delete
first.getSingleRelationship(RelTypes.KNOWS, Direction.OUTGOING).delete();
System.out.println("Nodes are removed");
// delete nodes
first.delete();
second.delete();
transaction.success();
}
finally
{
// finish the transaction
transaction.finish();
}
}
void shutDown ()
{
// shut down graphDataService
graphDataService.shutdown();
System.out.println("Neo4J database is shutdown");
}
}
and now I have the query part:
try ( Transaction ignored = db.beginTx();
Result result = db.execute( "match (n {name: 'my node'}) return n, n.name" ) )
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
so,,, first of all how to include the second part of the code to the first one, may be I did not put it in the right place, the second thing : the error is {result can not be resolved}
I am very new to graph-db and now I'm trying to do basics of that using examples. below is the sample code which i tried and I am trying to make relationship between three nodes. I am trying to get the below as o/p.
my code
private static final String DB_PATH = "/home/nnn/Documents/softwares/neo4j-community-2.0.1";
public String greeting;
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Node thirdNode;
Relationship relationship;
private static enum RelTypes implements RelationshipType
{
LIKES
}
public static void main( final String[] args )
{
G1 hello = new G1();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb()
{
clearDb();
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
registerShutdownHook( graphDb );
try ( Transaction tx = graphDb.beginTx() )
{
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Alice " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "Bob" );
thirdNode = graphDb.createNode();
thirdNode.setProperty( "message", "Anu" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.LIKES);
relationship.setProperty( "message", "likes " );
relationship = firstNode.createRelationshipTo( thirdNode, RelTypes.LIKES);
relationship.setProperty( "message", "likes " );
System.out.print( firstNode.getProperty("message"));
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
System.out.print( firstNode.getProperty( "message" ) );
//System.out.print( relationship.getProperty( "message" ) );
//System.out.print( thirdNode.getProperty( "message" ) );
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) )
+ ( (String) thirdNode.getProperty( "message" ) );
tx.success();
}
}
private void clearDb()
{
try
{
FileUtils.deleteRecursively( new File( DB_PATH ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
void removeData()
{
try ( Transaction tx = graphDb.beginTx() )
{
firstNode.getSingleRelationship( RelTypes.LIKES, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
thirdNode.delete();
tx.success();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
graphDb.shutdown();
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
As the exception indicates, you're calling
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
when you have more than one outgoing relation of type KNOWS from firstNode
(firstNode->secondNode and firstNode->thirdNode)
Maybe you want to use http://api.neo4j.org/2.0.1/org/neo4j/graphdb/Node.html#getRelationships(org.neo4j.graphdb.RelationshipType,%20org.neo4j.graphdb.Direction) instead
As for the output, you want to get all the relations from the first node to be able to get the end node of each relation.
You created two outgoing KNOWS relationships for your firstNode.
If you want to delete them all do:
for (Relationship rel : node.getRelationships()) {
rel.delete();
}
You can pass direction and type parameters to that method too.
But if you want to delete a node, all its relationships have to be deleted first.
For the life of me, I cannot understand why I am unable to read a graph I already created in neo4j 1.9.4 community edition. In eclipse, I run the following code:
public class neo4jtest {
private GraphDatabaseService graphDb;
private static final String neo4j_db = "c:/tmp/db/neo4j-new-db";
private UniqueFactory<Node> nodefactory;
private static enum RelTypes implements RelationshipType
{
FRIEND, FOLLOWER
}
public neo4jtest() {
graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(neo4j_db).
setConfig( GraphDatabaseSettings.node_keys_indexable, "ScreenName,ID" ).
setConfig( GraphDatabaseSettings.relationship_keys_indexable, (RelTypes.FRIEND).name()+","+(RelTypes.FOLLOWER).name()).
setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ).
setConfig( GraphDatabaseSettings.relationship_auto_indexing, "true" ).
newGraphDatabase();
//graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(neo4j_db);
registerShutdownHook( graphDb );
nodefactory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
{
#Override
protected void initialize( Node created, Map<String, Object> properties )
{
created.setProperty( "ScreenName", properties.get( "ScreenName" ) );
}
};
}
public void exit() {
graphDb.shutdown();
}
public static void main(String[] args) {
neo4jtest n4 = new neo4jtest();
String u1 = "Moe";
//Node unode = n4.createNeo4jGraph(u1);
n4.exploreNeo4jGraph(u1);
n4.exit();
}
public Node createNeo4jGraph(String uname) {
Node firstNode;
Relationship relationship;
// build a graph
try {
Transaction tx = graphDb.beginTx();
firstNode = nodefactory.getOrCreate("ScreenName", uname);
firstNode.setProperty( "ScreenName", uname );
firstNode.setProperty("ID", 1);
Node followerNode = nodefactory.getOrCreate("ScreenName", "Larry");
followerNode.setProperty("ID", 2);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
followerNode = nodefactory.getOrCreate("ScreenName", "Curly");
followerNode.setProperty("ID", 3);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
tx.success();
return firstNode;
} catch(Exception ex) {}
return null;
}
private void exploreNeo4jGraph(String scname) {
// use the auto indexer to lookup node with string name
// Get the Node auto index
ReadableIndex<Node> autoNodeIndex = graphDb.index()
.getNodeAutoIndexer()
.getAutoIndex();
Node mainUser = autoNodeIndex.get( "ScreenName", scname ).getSingle();
if (mainUser==null) {
// why not use nodefactory to get it?
System.out.println("Auto indexer did not work");
mainUser = nodefactory.getOrCreate("ScreenName", scname);
}
exploreNeo4jGraph(mainUser);
}
private void exploreNeo4jGraph(Node unode) {
// explore the nodes and edges in the graph
if (unode==null) {
System.err.println("Cannot explore from null node!");
return;
}
long currRels = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllRelationships());
long currNodes = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllNodes());
System.out.println("Number of nodes in graph is " + currNodes);
System.out.println("Number of edges in graph is " + currRels);
int numberOfFollowers = 0;
String output = unode.getProperty( "ScreenName" ) + "'s friends:\n";
Traverser friendsTraverser = getFriends( unode );
for ( Path friendPath : friendsTraverser )
{
output += "At depth " + friendPath.length() + " <= "
+ friendPath.endNode().getProperty( "ScreenName" ) + "\n";
numberOfFollowers++;
}
output += "Number of friends found: " + numberOfFollowers + "\n";
System.out.println(output);
}
private Traverser getFriends(final Node person )
{
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships( RelTypes.FRIEND, Direction.INCOMING )
.evaluator( Evaluators.excludeStartPosition() );
return td.traverse( person );
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
Basically, I uncomment line
Node unode = n4.createNeo4jGraph(u1);
to create the graph.
Then run it again with that line commented to just explore the graph that was created. When I run it again, it does not report the graph that was created. What am I doing wrong?
Thanks,
D
I'd guess you need to close the transaction. From the javadoc:
finish() (in 1.9)
Commits or marks this transaction for rollback, depending on whether success() or failure() has been previously invoked.
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