text assigned to String attribute does not store properly - text

I have assigned a text from a txt file to three attributes, but whenever I call any of those attributes with a Get Method to another class, the value displayed is "null".
Furthermore, I have confirmed that these values are displayed in the method leerArchivo (whenever I use a println for m_linea1-2-3).
Please Help.
public class ArchivoCasillas
{
String m_linea1;
String m_linea2;
String m_linea3;
public void crearArchivo()
{
try
{
FileWriter fw = new FileWriter("ReglasDelTablero.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(fw);
bw.write("<7,0> , <0,0>");
bw.newLine();
bw.write("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>");
bw.newLine();
bw.write("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>");
bw.close();
}
catch(IOException e)
{
System.out.println("error");
}
}
public void leerArchivo()
{
String linea;
int i = 1;
try
{
FileReader fr = new FileReader("ReglasDelTablero.txt");
BufferedReader br = new BufferedReader(fr);
Tablero serpientesEscaleras = new Tablero();
while( (linea = br.readLine() ) != null)
{
switch(i)
{
case 1: m_linea1 = linea;
break;
case 2: m_linea2 = linea;
break;
case 3: m_linea3 = linea;
break;
}
i++;
}
br.close();
}
catch(IOException e)
{
}
}
public String getM_linea1()
{
return m_linea1;
}
}

Problem solved. It was a conceptual problem on my part. I created an Object in another class, but I never called the leerArchivo method with that object, therefore, the value of the attributes was null. Leaving an answer in case it's useful for someone in the future, as I didn't get a reply.

Related

How can I read the schema (XSD) from Saxon after loading an XML & XSD file?

Our program displays a tree control showing the metadata structure of the XML file they are using as a datasource. So it displays all elements & attributes in use in the XML file, like this:
Employees
Employee
FirstName
LastName
Orders
Order
OrderId
For the case where the user does not pass us a XSD file, we need to walk the XML file and build up the metadata structure.
The full code for this is at SaxonQuestions.zip, TestBuildTreeWithSchema.java and is also listed below.
The below code works but it has a problem. Suppose under Employee there's an element for SpouseName. This is only populated if the employee is married. What if the sample data file I have is all unmarried employees? Then the below code does not know there's a SpouseName element.
So my question is - how can I read the schema directly, instead of using the below code. If I read the schema then I get every node & attribute including the optional ones. I also get the type. And the schema optionally has a description for each node and I get that too.
Therefore, I need to read the schema itself. How can I do that?
And secondary question - why is the type for an int BigInteger instead of Integer or Long? I see this with Employee/#EmployeeID in Southwind.xml & Southwind.xsd.
TestBuildTreeWithSample.java
import net.sf.saxon.s9api.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class TestBuildTreeWithSchema {
public static void main(String[] args) throws Exception {
XmlDatasource datasource = new XmlDatasource(
new FileInputStream(new File("files", "SouthWind.xml").getCanonicalPath()),
new FileInputStream(new File("files", "SouthWind.xsd").getCanonicalPath()));
// get the root element
XdmNode rootNode = null;
for (XdmNode node : datasource.getXmlRootNode().children()) {
if (node.getNodeKind() == XdmNodeKind.ELEMENT) {
rootNode = node;
break;
}
}
TestBuildTreeWithSchema buildTree = new TestBuildTreeWithSchema(rootNode);
Element root = buildTree.addNode();
System.out.println("Schema:");
printElement("", root);
}
private static void printElement(String indent, Element element) {
System.out.println(indent + "<" + element.name + "> (" + (element.type == null ? "null" : element.type.getSimpleName()) + ")");
indent += " ";
for (Attribute attr : element.attributes)
System.out.println(indent + "=" + attr.name + " (" + (attr.type == null ? "null" : attr.type.getSimpleName()) + ")");
for (Element child : element.children)
printElement(indent, child);
}
protected XdmItem currentNode;
public TestBuildTreeWithSchema(XdmItem currentNode) {
this.currentNode = currentNode;
}
private Element addNode() throws SaxonApiException {
String name = ((XdmNode)currentNode).getNodeName().getLocalName();
// Question:
// Is this the best way to determine that this element has data (as opposed to child elements)?
Boolean elementHasData;
try {
((XdmNode) currentNode).getTypedValue();
elementHasData = true;
} catch (Exception ex) {
elementHasData = false;
}
// Questions:
// Is this the best way to get the type of the element value?
// Why BigInteger instead of Long for int?
Class valueClass = ! elementHasData ? null : ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Element element = new Element(name, valueClass, null);
// add in attributes
XdmSequenceIterator currentSequence;
if ((currentSequence = moveTo(Axis.ATTRIBUTE)) != null) {
do {
name = ((XdmNode) currentNode).getNodeName().getLocalName();
// Questions:
// Is this the best way to get the type of the attribute value?
// Why BigInteger instead of Long for int?
valueClass = ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Attribute attr = new Attribute(name, valueClass, null);
element.attributes.add(attr);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
// add in children elements
if ((currentSequence = moveTo(Axis.CHILD)) != null) {
do {
Element child = addNode();
// if we don't have this, add it
Element existing = element.getChildByName(child.name);
if (existing == null)
element.children.add(child);
else
// add in any children this does not have
existing.addNewItems (child);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
return element;
}
// moves to element or attribute
private XdmSequenceIterator moveTo(Axis axis) {
XdmSequenceIterator en = ((XdmNode) currentNode).axisIterator(axis);
boolean gotIt = false;
while (en.hasNext()) {
currentNode = en.next();
if (((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE) {
gotIt = true;
break;
}
}
if (gotIt) {
if (axis == Axis.ATTRIBUTE || axis == Axis.CHILD || axis == Axis.NAMESPACE)
return en;
return null;
}
return null;
}
// moves to next element or attribute
private Boolean moveToNextInCurrentSequence(XdmSequenceIterator currentSequence)
{
if (currentSequence == null)
return false;
while (currentSequence.hasNext())
{
currentNode = currentSequence.next();
if (((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE)
return true;
}
return false;
}
static class Node {
String name;
Class type;
String description;
public Node(String name, Class type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
}
static class Element extends Node {
List<Element> children;
List<Attribute> attributes;
public Element(String name, Class type, String description) {
super(name, type, description);
children = new ArrayList<>();
attributes = new ArrayList<>();
}
public Element getChildByName(String name) {
for (Element child : children) {
if (child.name.equals(name))
return child;
}
return null;
}
public void addNewItems(Element child) {
for (Attribute attrAdd : child.attributes) {
boolean haveIt = false;
for (Attribute attrExist : attributes)
if (attrExist.name.equals(attrAdd.name)) {
haveIt = true;
break;
}
if (!haveIt)
attributes.add(attrAdd);
}
for (Element elemAdd : child.children) {
Element exist = null;
for (Element elemExist : children)
if (elemExist.name.equals(elemAdd.name)) {
exist = elemExist;
break;
}
if (exist == null)
children.add(elemAdd);
else
exist.addNewItems(elemAdd);
}
}
}
static class Attribute extends Node {
public Attribute(String name, Class type, String description) {
super(name, type, description);
}
}
}
XmlDatasource.java
import com.saxonica.config.EnterpriseConfiguration;
import com.saxonica.ee.s9api.SchemaValidatorImpl;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.FeatureKeys;
import net.sf.saxon.s9api.*;
import net.sf.saxon.type.SchemaException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class XmlDatasource {
/** the DOM all searches are against */
private XdmNode xmlRootNode;
private XPathCompiler xPathCompiler;
/** key == the prefix; value == the uri mapped to that prefix */
private HashMap<String, String> prefixToUriMap = new HashMap<>();
/** key == the uri mapped to that prefix; value == the prefix */
private HashMap<String, String> uriToPrefixMap = new HashMap<>();
public XmlDatasource (InputStream xmlData, InputStream schemaFile) throws SAXException, SchemaException, SaxonApiException, IOException {
boolean haveSchema = schemaFile != null;
// call this before any instantiation of Saxon classes.
Configuration config = createEnterpriseConfiguration();
if (haveSchema) {
Source schemaSource = new StreamSource(schemaFile);
config.addSchemaSource(schemaSource);
}
Processor processor = new Processor(config);
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = createXMLReader();
InputSource xmlSource = new InputSource(xmlData);
SAXSource saxSource = new SAXSource(reader, xmlSource);
if (haveSchema) {
SchemaValidator validator = new SchemaValidatorImpl(processor);
doc_builder.setSchemaValidator(validator);
}
xmlRootNode = doc_builder.build(saxSource);
xPathCompiler = processor.newXPathCompiler();
if (haveSchema)
xPathCompiler.setSchemaAware(true);
declareNameSpaces();
}
public XdmNode getXmlRootNode() {
return xmlRootNode;
}
public XPathCompiler getxPathCompiler() {
return xPathCompiler;
}
/**
* Create a XMLReader set to disallow XXE aattacks.
* #return a safe XMLReader.
*/
public static XMLReader createXMLReader() throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
// stop XXE https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return reader;
}
private void declareNameSpaces() throws SaxonApiException {
// saxon has some of their functions set up with this.
prefixToUriMap.put("saxon", "http://saxon.sf.net");
uriToPrefixMap.put("http://saxon.sf.net", "saxon");
XdmValue list = xPathCompiler.evaluate("//namespace::*", xmlRootNode);
if (list == null || list.size() == 0)
return;
for (int index=0; index<list.size(); index++) {
XdmNode node = (XdmNode) list.itemAt(index);
String prefix = node.getNodeName() == null ? "" : node.getNodeName().getLocalName();
// xml, xsd, & xsi are XML structure ones, not ones used in the XML
if (prefix.equals("xml") || prefix.equals("xsd") || prefix.equals("xsi"))
continue;
// use default prefix if prefix is empty.
if (prefix == null || prefix.isEmpty())
prefix = "def";
// this returns repeats, so if a repeat, go on to next.
if (prefixToUriMap.containsKey(prefix))
continue;
String uri = node.getStringValue();
if (uri != null && !uri.isEmpty()) {
xPathCompiler.declareNamespace(prefix, uri);
prefixToUriMap.put(prefix, uri);
uriToPrefixMap.put(uri, prefix); }
}
}
public static EnterpriseConfiguration createEnterpriseConfiguration()
{
EnterpriseConfiguration configuration = new EnterpriseConfiguration();
configuration.supplyLicenseKey(new BufferedReader(new java.io.StringReader(deobfuscate(key))));
configuration.setConfigurationProperty(FeatureKeys.SUPPRESS_XPATH_WARNINGS, Boolean.TRUE);
return configuration;
}
}
Thanks for the clarifications. I think your real goal is to find a way to parse and process an XML Schema in Java without having to treat the XSD as an ordinary XML document (it is an ordinary XML document, but processing it using the standard facilities is not easy).
On that basis, I think this thread should help: In Java, how do I parse an xml schema (xsd) to learn what's valid at a given element?
Personally, I've never found any library that does a better job than the EMF XSD model. It's complex, but comprehensive.

How to avoid java.util.NoSuchElementException

The code below is giving me the error java.util.NoSuchElementException right after I Ctrl+Z
to indicate that the user input is complete. By the looks of it seems as if it does not know how to just end one method without messing with the other scanner object.
I try the hasNext method and I ended up with an infinite loop, either way is not working. As a requirement for this assignment I need to be able to tell the user to use Ctrl+Z or D depending on the operating system. Also I need to be able to read from a text file and save the final tree to a text file please help.
/* sample input:
CSCI3320
project
personal
1 HW1
1 HW2
1 2 MSS.java
2 p1.java
*/
import java.util.Scanner;
import java.util.StringTokenizer;
public class Directory {
private static TreeNode root = new TreeNode("/", null, null);
public static void main(String[] args) {
userMenu();
System.out.println("The directory is displayed as follows:");
root.listAll(0);
}
private static void userMenu(){ //Displays users menu
Scanner userInput = new Scanner(System.in);//Scanner option
int option = 0;
do{ //I believe the problem is here since I am not using userInput.Next()
System.out.println("\n 1. add files from user inputs ");
System.out.println("\n 2. display the whole directory ");
System.out.println("\n 3. display the size of directory ");
System.out.println("\n 0. exit");
System.out.println("\n Please give a selection [0-3]: ");
option = userInput.nextInt();
switch(option){
case 1: addFileFromUser();
break;
case 2: System.out.println("The directory is displayed as follows:");
root.listAll(0);
break;
case 3: System.out.printf("The size of the directory is %d.\n", root.size());
break;
default:
break;
}
}while( option !=0);
userInput.close();
}
private static void addFileFromUser() {
System.out.println("To terminate inp1ut, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) { //hasNext being used Crtl Z is required to break
addFileIntoDirectory(input); // out of the loop.
}
input.close();
}
private static void addFileIntoDirectory(Scanner input) {
String line = input.nextLine();
if (line.trim().equals("")) return;
StringTokenizer tokens = new StringTokenizer(line);
int n = tokens.countTokens() - 1;
TreeNode p = root;
while (n > 0 && p.isDirectory()) {
int a = Integer.valueOf( tokens.nextToken() );
p = p.getFirstChild();
while (a > 1 && p != null) {
p = p.getNextSibling();
a--;
}
n--;
}
String name = tokens.nextToken();
TreeNode newNode = new TreeNode(name, null, null);
if (p.getFirstChild() == null) {
p.setFirstChild(newNode);
}
else {
p = p.getFirstChild();
while (p.getNextSibling() != null) {
p = p.getNextSibling();
}
p.setNextSibling(newNode);
}
}
private static class TreeNode {
private String element;
private TreeNode firstChild;
private TreeNode nextSibling;
public TreeNode(String e, TreeNode f, TreeNode s) {
setElement(e);
setFirstChild(f);
setNextSibling(s);
}
public void listAll(int i) {
for (int k = 0; k < i; k++) {
System.out.print('\t');
}
System.out.println(getElement());
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
t.listAll(i+1);
t = t.getNextSibling();
}
}
}
public int size() {
int s = 1;
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
s += t.size();
t = t.getNextSibling();
}
}
return s;
}
public void setElement(String e) {
element = e;
}
public String getElement() {
return element;
}
public boolean isDirectory() {
return getFirstChild() != null;
}
public void setFirstChild(TreeNode f) {
firstChild = f;
}
public TreeNode getFirstChild() {
return firstChild;
}
public void setNextSibling(TreeNode s) {
nextSibling = s;
}
public TreeNode getNextSibling() {
return nextSibling;
}
}
}
Exception Details:
/*Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Directory.userMenu(Directory.java:36)
at Directory.main(Directory.java:21)*/
Your problem is this line:
option = userInput.nextInt(); //line 24
If you read the Javadoc, you will find that the nextInt() method can throw a NoSuchElementException if the input is exhausted. In other words, there is no next integer to get. Why is this happening in your code? Because you this line is in a loop once that first iteration completes (on the outer while loop) your initial input selection has been consumed. Since this is a homework, I am not going to write the code. But, if you remove the loop, you know this works at least once. Once you try to loop, it breaks. So I will give you these hints:
Change the do/while to a while loop.
Prompt the user once outside the loop.
Recreate the prompt and recapture the user input inside the loop.
For example, the code below can be used for the basis of your outer loop.
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Guess the secret number: (Hint: the secret number is 1)");
int guess = input.nextInt();
while (guess != 1) {
System.out.println("Wrong guess. Try again: ");
guess = input.nextInt();
}
System.out.println("Success");
input.close();
}
}
The reason why this works is because I don't reuse the same, exhausted, scanner input object to get the next integer. In your example, the initial input is inside the loop. The second time around, that input has already been consumed. Follow this pattern and you should be able to complete your assignment.

I'm getting Resource Leaks

Whenever I run this code, it works pretty smoothly, until the while loop runs through once. It will go back and ask for the name again, and then skip String b = sc.nextLine();, and print the next line, instead.
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
Also, I'm trying to create this program in a way that I can ask three questions (like someone's Name, Gender, and Age, maybe more like race and whatnot), and then bring all of those answers back. Like, at the very end, say, "So, your name is + name +, you are + gender +, and you are + age + years old? Yes/No." Something along those lines. I know there's a way to do it, but I don't know how to save those responses anywhere, and I can't grab them since they only occur in the instance of the method.
Don't try to scan text with nextLine() AFTER using nextInt() with the same scanner! It may cause problems. Open a scanner method for ints only...it's recommended.
You could always parse the String answer of the scanner.
Also, using scanner this way is not a good practice, you could organize questions in array an choose a loop reading for a unique scanner instantiation like this:
public class a {
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
static Scanner sc ;
static public void main(String [] argv) {
Name();
}
static public void Name() {
sc = new Scanner(System.in);
String[] questions = {"Name?","Age","Sex?"};//
int a = 0;
System.out.println(questions[a]);
while (sc.hasNext()) {
input = sc.next();
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine " + InputName
+ " so you are " + Age + " years old and " + Sex + "." );
Age = null;
Sex = null;
InputName = null;
System.out.println("Loop again?");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
}
}
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
}
}
}
Pay attention on the global variables, wich stores your info until you set them null or empty...you could use them to the final affirmation.
Hope this helps!
Hope this helps!

Google API throws exception at specified lat & long position?

Below is my sample code
public static string GetGeoLoc(string latitude, string longitude,
out string Address_ShortCountryName,
out string Address_country,
out string Address_administrative_area_level_1,
out string Address_administrative_area_level_1_short_name,
out string Address_administrative_area_level_2,
out string Address_administrative_area_level_3,
out string Address_colloquial_area,
out string Address_locality,
out string Address_sublocality,
out string Address_neighborhood)
{
Address_ShortCountryName = "";
Address_country = "";
Address_administrative_area_level_1 = "";
Address_administrative_area_level_1_short_name = "";
Address_administrative_area_level_2 = "";
Address_administrative_area_level_3 = "";
Address_colloquial_area = "";
Address_locality = "";
Address_sublocality = "";
Address_neighborhood = "";
XmlDocument doc = new XmlDocument();
try
{
doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" + latitude + "," + longitude + "&sensor=false");
XmlNode element = doc.SelectSingleNode("//GeocodeResponse/status");
if (element.InnerText == "ZERO_RESULTS")
{
return ("No data available for the specified location");
}
else
{
element = doc.SelectSingleNode("//GeocodeResponse/result/formatted_address");
string longname = "";
string shortname = "";
string typename = "";
XmlNodeList xnList = doc.SelectNodes("//GeocodeResponse/result/address_component");
foreach (XmlNode xn in xnList)
{
try
{
longname = xn["long_name"].InnerText;
shortname = xn["short_name"].InnerText;
typename = xn["type"].InnerText;
switch (typename)
{
case "country":
{
Address_country = longname;
Address_ShortCountryName = shortname;
break;
}
case "locality":
{
Address_locality = longname;
break;
}
case "sublocality":
{
Address_sublocality = longname;
break;
}
case "neighborhood":
{
Address_neighborhood = longname;
break;
}
case "colloquial_area":
{
Address_colloquial_area = longname;
break;
}
case "administrative_area_level_1":
{
Address_administrative_area_level_1 = longname;
Address_administrative_area_level_1_short_name = shortname;
break;
}
case "administrative_area_level_2":
{
Address_administrative_area_level_2 = longname;
break;
}
case "administrative_area_level_3":
{
Address_administrative_area_level_3 = longname;
break;
}
default:
break;
}
}
catch (Exception e)
{
clsExHandler.Instance.Write(e);
}
}
return (element.InnerText);
}
}
catch (Exception ex)
{
return ("(Address lookup failed: ) " + ex.Message);
}
}
try passing latitude as 33.4965 & longitude as -112.205
i'm getting an exception object reference to invalid object in the line
**typename = xn["type"].InnerText;**
when i debug step by step there is no such attribute like ["type"]
Also there are some other lingual character why?
How could i resolve this issue.
I'm not familiar with c# and Im not sure if your code is correct at all(e.g. types is not an attribute, it's an elementNode).
Assuming that your code is correct and you can select nodes by using node['nameOfChildNode'] , when you inspect the XML-File: http://maps.googleapis.com/maps/api/geocode/xml?latlng=33.4965,-112.205&sensor=false you will see that there are address_components with 2 <type>'s and also address_components without any <type> .
I guess your code breaks not at the missing <type>, it breaks when you try to access a property(InnerText) of the missing <type>.
What you can do: use selectSingleNode to select the <type> and when it returns null implement a fallback or leave the further processing.
http://maps.googleapis.com/maps/api/geocode/json?latlng=33.4965%20,%20-112.205&sensor=false
returns
{
"results" : [],
"status" : "ZERO_RESULTS"
}
Therefore
XmlNode element = doc.SelectSingleNode("//GeocodeResponse/status");
if (element.InnerText == "ZERO_RESULTS")
{
return ("No data available for the specified location");
}
is not catching ZERO_RESULTS.
I am not familiar with C# so I cannot help further.

Validation in swt text

I would like to validate numbers input in text box.
I want the user to input only integer, decimal in the box between a maximum and minimum values.
How can I make sure of this?
Thank you.
Use a VerifyListener as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
You can register a ModifyListener with the text control and use it to validate the number.
txt.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent event) {
String txt = ((Text) event.getSource()).getText();
try {
int num = Integer.parseInt(txt);
// Checks on num
} catch (NumberFormatException e) {
// Show error
}
}
});
You could also use addVerifyListener to prevent certain characters being entered. In the event passed into that method there is a "doit" field. If you set that to false it prevents the current edit.
Integer validation in SWT
text = new Text(this, SWT.BORDER);
text.setLayoutData(gridData);
s=text.getText();
this.setLayout(new GridLayout());
text.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
});
If you only want to allow Integer values you could use a Spinner instead of a text field.
For the validation of Double values you have to consider that characters like E may be included in Doubles and that partial input like "4e-" should be valid while typing. Such partial expressions will give a NumberFormatException for Double.parseDouble(partialExpression)
Also see my answer at following related question:
How to set a Mask to a SWT Text to only allow Decimals
1.create a utill class implement verify listener
2.override verifytext method
3.implement your logic
4.create a object of utill class where you want to use verify listener (on text)
5.text.addverifylistener(utillclassobject)
Example :-
1. utill class:-
public class UtillVerifyListener implements VerifyListener {
#Override
public void verifyText(VerifyEvent e) {
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
2.use of verifylistener in other class
public class TestVerifyListenerOne {
public void createContents(Composite parent){
UtillVerifyListener listener=new UtillVerifyListener();
textOne = new Text(composite, SWT.BORDER);
textOne .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textOne .addVerifyListener(listener)
textTwo = new Text(composite, SWT.BORDER);
textTwo .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textTwo .addVerifyListener(listener);
}
}
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
Text text = (Text) e.getSource();
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isValid = true;
try {
if(! "".equals(newS)){
Float.parseFloat(newS);
}
} catch (NumberFormatException ex) {
isValid = false;
}
e.doit = isValid;
}
});

Resources