Null pointer exception when parsing Node Value in Blackberry [duplicate] - blackberry

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse empty node value in Blackberry
I am getting the response from web service as below.
<section id="2"></section>
<section id="2">xxx</section>
Now to parse the above response i wrote the code as below
speakersnode=speaker.getElementsByTagName("section");
for(int k=0;k<speakersnode.getLength();k++)
{
System.out.println("speaker "+speakersnode.item(k).getFirstChild().getNodeValue());
vspeakers.addElement(speakersnode.item(k).getFirstChild().getNodeValue());
}
When i parsing it i am getting null pointer exception here.
Now i chaged the code as follow
speakersnode=speaker.getElementsByTagName("section");
for(int k=0;k<speakersnode.getLength();k++)
{
if(speakersnode.item(k).getFirstChild().getNodeValue() !=null)
{
System.out.println("speaker "+speakersnode.item(k).getFirstChild().getNodeValue());
vspeakers.addElement(speakersnode.item(k).getFirstChild().getNodeValue());
}
}
But still i am getting the null pointer exception how

Try this:
speakersnode=speaker.getElementsByTagName("speaker");
for(int k=0;k<speakersnode.getLength();k++)
{
ids.addElement(((Element)speakersnode.item(k)).getAttribute("id"));
String info = speakersnode.item(k).getFirstChild().getNodeValue();
if (info == null){
info = "";
}
System.out.println("speaker "+ info );
vspeakers.addElement(info);
}
You also need to learn how to debug. And how to handle exceptions. You will lear how to fix this kind of stuff in seconds

Related

How to read json file from ESP8266's SPIFFS with ArduinoJSON 6?

I am currently working on a project with ESP8266 (ESP-12E) and I need to store information in a json file (more convenient to access via the web interface and easier to manage than EEPROM for me).
My problem is the following: I'm using the latest version of ArduinoJSON (6), but I haven't seen many examples except on their site, and this code doesn't work for me :
void DeleteCycle(size_t idtodelete) {
File schedules = SPIFFS.open("/schedules.json", "r");
if(schedules && schedules.size()) {
DynamicJsonDocument schedulesjson(1300);
DeserializationError err = deserializeJson(schedulesjson, schedules);
Serial.println(err.c_str());
if (err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.c_str());
}
else {
JsonArray array = schedulesjson.to<JsonArray>();
// array.remove(0);
serializeJson(array, Serial);
}
schedules.close();
}
else {
Serial.println("Failed to read file.");
}
}
I guess the problem is the JsonArray, it's empty !
But my JsonDocument is not, because if I do
JsonObject obj = schedulesjson[0];
String test = obj["name"];
Serial.println("Test : " + test);
I get the first key value (name) of my array at index 0
This is my first post on StackOverflow, I hope I did it right, thanks in advance for your help!
I answer myself because I found the solution to my problem: writing
schedulesjson.to<JsonArray>();
empties the json document, so you have to put it before
DeserializationError err = deserializeJson(schedulesjson, schedules);

neo4j 2.0 findNodesByLabelAndProperty not working

I'm currently trying the Neo4j 2.0.0 M3 and see some strange behaviour. In my unit tests, everything works as expected (using an newImpermanentDatabase) but in the real thing, I do not get results from the graphDatabaseService.findNodesByLabelAndProperty.
Here is the code in question:
ResourceIterator<Node> iterator = graphDB
.findNodesByLabelAndProperty(Labels.User, "EMAIL_ADDRESS", emailAddress)
.iterator();
try {
if (iterator.hasNext()) { // => returns false**
return iterator.next();
}
} finally {
iterator.close();
}
return null;
This returns no results. However, when running the following code, I see my node is there (The MATCH!!!!!!!!! is printed) and I also have an index setup via the schema (although that if I read the API, this seems not necessary but is important for performance):
ResourceIterator<Node> iterator1 = GlobalGraphOperations.at(graphDB).getAllNodesWithLabel(Labels.User).iterator();
while (iterator1.hasNext()) {
Node result = iterator1.next();
UserDao.printoutNode(emailAddress, result);
}
And UserDao.printoutNode
public static void printoutNode(String emailAddress, Node next) {
System.out.print(next);
ResourceIterator<Label> iterator1 = next.getLabels().iterator();
System.out.print("(");
while (iterator1.hasNext()) {
System.out.print(iterator1.next().name());
}
System.out.print("): ");
for(String key : next.getPropertyKeys()) {
System.out.print(key + ": " + next.getProperty(key).toString() + "; ");
if(emailAddress.equals( next.getProperty(key).toString())) {
System.out.print("MATCH!!!!!!!!!");
}
}
System.out.println();
}
I already debugged through the code and what I already found out is that I pass via the InternalAbstractGraphDatabase.map2Nodes to a DelegatingIndexProxy.getDelegate and end up in IndexReader.Empty class which returns the IteratorUtil.EMPTY_ITERATOR thus getting false for iterator.hasNext()
Any idea's what I am doing wrong?
Found it:
I only included neo4j-kernel:2.0.0-M03 in the classpath. The moment I added neo4j-cypher:2.0.0-M03 all was working well.
Hope this answer helps save some time for other users.
#Neo4j: would be nice if an exception would be thrown instead of just returning nothing.
#Ricardo: I wanted to but I was not allowed yet as my reputation wasn't good enough as a new SO user.

ObjectStore put syntax

I'm having trouble with the new syntax (r18915) for idb.ObjectStore.put. Could someone please help?
example is below which results in error as follows :
AsyncError: ‘Error:DataError: DOM IDBDatabase Exception 0’
Stack trace: #0 ObjectStore._put_2(file:///E:/b/build/slave/dartium-win-full-trunk/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:141:3) #1
ObjectStore.$dom_put(file:///E:/b/build/slave/dartium-win-full-trunc/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:137:18) #2
ObjectStore.put(file:///E:/b/build/slave/dartium-win-full-trunc/build/src/build/Release/obj/
global_intermediate/webkit/bindings/dart/indexed_db/ObjectStore.dart:9:27)
The code I'm using which was working but has been modified for new release as follows :
Future fDbAddOrUpdateClient(String sKey1, ClassClientData clClientData) {
idb.Transaction oDbTxn = ogDb1.transaction(sgStoreClient, 'readwrite');
idb.ObjectStore oDbStoreClient = oDbTxn.objectStore(sgStoreClient);
Completer completer = new Completer();
var oDbReqPut = oDbStoreClient.put(
{'sKey': sKey1,
'sNameTitle' : clClientData.sNameTitle,
'sNameFamily' : clClientData.sNameFamily,
'sNameGiven1' : clClientData.sNameGiven1,
'sNameGiven2' : clClientData.sNameGiven2
})
.then((val){
completer.complete(val);
return;
})
.catchError((e){
window.alert("${e}");
return;
});
}
Apart from the future you specify your function returns but never does, only a completed value (as mentioned in other comment), the future syntax appears correct. The error itself actually indicates that the data being passed to your objectstore.put command is invalid.
See IndexedDB Exceptions. You may need to verify the data that is being passed to the map.
Thanks for the help. The main problem appeared to be with Database not opening or something related such as ObjectStore not being created, but no error shown.
Hopefully the following is better code (r19425) :
Future future = fDbAddOrUpdateClient(sKey, clClientData)
.catchError((oError) => window.alert("${oError}"));
}
Future fDbAddOrUpdateClient(String sKey1, ClassClientData clClientData) {
idb.Transaction oDbTxn = ogDb1.transaction(sgStoreClient, 'readwrite');
idb.ObjectStore oDbStoreClient = oDbTxn.objectStore(sgStoreClient);
return oDbStoreClient.put(fMapClient(sKey1, clClientData));
}

php DomDocument : Match each nodeValue, add attribute to its nodeName if condition satisfies [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Check for each text node whether or not it exists in DataBase, if it does then add a class to its Element node.
I have tried do it the following way :
function extractText($node) {
if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
// am considering that Login is the word that exists in DB
if ($node->nodeValue == "Login"):
$node->setAttribute("class", "translated");
return $node->nodeName;
endif;
} else if (XML_ELEMENT_NODE === $node->nodeType || XML_DOCUMENT_NODE === $node->nodeType
|| XML_DOCUMENT_FRAG_NODE === $node->nodeType) {
if ('script' === $node->nodeName || 'style' === $node->nodeName)
return '';
$text = '';
foreach ($node->childNodes as $childNode) {
$text .= extractText($childNode);
}
return $text;
}
}
$doc = new DomDocument;
$doc->loadHTMLFile('test.html');
//var_dump(extractText($doc->getElementsByTagName('body')->item(0)));
echo extractText($doc->getElementsByTagName('body')->item(0));
But it gives Error message.
Fatal error: Call to undefined method DOMText::setAttribute()
Fatal error: Call to undefined method DOMText::setAttribute()
Well, let's look at the code.
if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
// am considering that Login is the word that exists in DB
if ($node->nodeValue == "Login"):
$node->setAttribute("class", "translated");
return $node->nodeName;
endif;
} /* else ... */
You're asking exclusively for text or CDATA nodes, then you're trying to set an attribute ... on the text. This won't work. Text nodes can't have attributes.
You need to get to the element containing the text and add the attribute there. Because DOMText inherits from DOMNode, you can inspect the parentNode property and probably get an element back.

The youtube API sometimes throws error: Call to a member function children() on a non-object

When i launch the php script, sometime works fine, but many other times it retrieve me this errror
Fatal error: Call to a member function children() on a non-object in
/membri/americanhorizon/ytvideo/rilevametadatadaurlyoutube.php on line
21
This is the first part of the code
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/dZec2Lbr_r8';
// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);
$video = parseVideoEntry($entry);
function parseVideoEntry($entry) {
$obj= new stdClass;
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/'); //<----this is the doomed line 21
UPDATE: solution adopted
for ($i=0 ; $i< count($fileArray); $i++)
{
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$fileArray[$i];
// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);
if (is_object($entry))
{
$video = parseVideoEntry($entry);
echo ($video->description."|".$video->length);
echo "<br>";
}
else
{
$i--;
}
}
In this mode i force the script to re-check the file that caused the error
You are first of all calling a function:
$entry = simplexml_load_file($feedURL);
That function has a return value. You find it documented on the manual page of that function:
http://php.net/simplexml_load_file
Then you use that return value in form of a variable $entry without verifying that the function call was successful.
Because of that, you run into an error next. However your error/mistake is how you treat the return value of the function.
Not dealing with return values properly is like calling for trouble. Read about the function you use, check the return value(s) and proceed according to success or error conditions.
$entry = simplexml_load_file($feedURL);
if (FALSE === $entry)
{
// youtube not available.
}
else
{
// that's what I love!
}
Sometimes? Really?
Take a look at this:
<?php
$dummy; //IN FACT, this var is NULL now
// Will throw exactly the same error you get
$dummy->children();
Why? Because, we can call method from an object type.
So, if you wanna avoid errors like this one, next time you would call the method ensure that it's "possible".
<?php
if ( is_object($dummy) && method_exists($dummy, 'children') ){
//sure it works
$dummy->children();
}

Resources