I have created a delete method.
My method has an index as argument that comes from a jlist position.
The method will get the position from the jlist that the user have clicked and look up that element in the xml and delete it and all children.
So if user click TrainCategorySpeed it has index 122 and will look for that type in the XML
<type>
<OBJECT_TYPE>TrainCategorySpeed</OBJECT_TYPE>
- <prop>
<DESCRIPTION>Differential speed limit</DESCRIPTION>
<PARENT>NULL</PARENT>
<VIRTUAL>0</VIRTUAL>
<VISIBLE>0</VISIBLE>
<PICTURE>NULL</PICTURE>
<HELP>NULL</HELP>
<MIN_NO>NULL</MIN_NO>
<MAX_NO>NULL</MAX_NO>
<NAME_FORMAT>NULL</NAME_FORMAT>
</prop>
- <param>
<PARAMETER>trainCategory</PARAMETER>
<DATA_TYPE>INTEGER</DATA_TYPE>
<DESCRIPTION>Train category</DESCRIPTION>
<MIN_NO>1</MIN_NO>
<MAX_NO>1</MAX_NO>
<ORDER1>1</ORDER1>
<NESTED>1</NESTED>
<DEFAULT1>NULL</DEFAULT1>
<FORMAT>0:15</FORMAT>
</param>
- <param>
<PARAMETER>speed</PARAMETER>
<DATA_TYPE>INTEGER</DATA_TYPE>
<DESCRIPTION>Speed (km/h (V_DIFF))</DESCRIPTION>
<MIN_NO>1</MIN_NO>
<MAX_NO>1</MAX_NO>
<ORDER1>2</ORDER1>
<NESTED>1</NESTED>
<DEFAULT1>NULL</DEFAULT1>
<FORMAT>0:600:5</FORMAT>
</param>
</type>
But when I am trying to achieve this it gives me a nullpointer exception
on the follwoing line : Node type = doc.getElementsByTagName("type").item(x);
x here is really giving correct position and type is the element in the xml.
but the type is null.
This is the rest of the method :
public void deleteObjType(int x) {
System.out.println("index : " + x); // This one will return index : 122 in the console and it does
File file = new File("xmlFiles/CoreDatamodel.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder = builderFactory.newDocumentBuilder();
Document doc = builder.parse(file);
Node type = doc.getElementsByTagName("type").item(x);
System.out.println("type : " + type);
NodeList nodes = type.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node element = nodes.item(x);
System.out.println("element : " + element);
// remove node
if ("OBJECT_TYPE".equals(element.getNodeName())) {
type.removeChild(element);
}
}
// Save the new update
save(file, doc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Full stacktrace:
java.lang.NullPointerException
at cxmleditor.service.XMLEditorService.deleteObjType(XMLEditorService.java:106)
at xmleditor.gui.XmlEditorMain$deleteObjType.actionPerformed(XmlEditorMain.java:383)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I think your problem is the following line:
for (int i = 0; i < nodes.getLength(); i++) {
Note that i should not increment when you delete a node.
The problem is not necessarily that your type object is null. When deleteObjType(0); is called on the simple xml you provided,
System.out.println("type : " + type);
only uses the toString()-method of the type object instance and prints out:
type : [type: null]
if you instead do
System.out.println("type : " +type);
if(type == null) {
System.out.println("type is null!");
}else {
System.out.println("type is not null but an instance of ["+type.getClass().getCanonicalName()+"]");
}
it prints in my case:
type is not null but an instance of [com.sun.org.apache.xerces.internal.dom.DeferredElementImpl]
DOM is also a bit more complex than element nodes having direct element nodes as children as you can see here . I've learned through practice that simply printing out the nodes is usually not enough.
Which part of the xml do you actually want to remove?
Related
I'm getting
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1
when I'm deleting last Item in JComboBox. Anyone knows why?
cb = new JComboBox<String>();
bComboDelete.addActionListener(this);
bComboDelete = new JButton("X"); //deletes item from CB
bComboAccept = new JButton("#");// add an item
ArrayList<String> names = new ArrayList<String>(); //get name, runs with sNumbers
ArrayList<String> sNumbers = new ArrayList<String>();//some String numbers ----> e.g. [[1, 2, 3],[4, 5, 6]]
ArrayList<Integer> numbers = new ArrayList<Integer>(); //array to temp hold numbers
//***ending code from ActionListener
else if(s == bComboAccept)
{
sNumbers.add(numbers.toString());
//System.out.println(sNumbers);
names.add(tName.getText());//tName is JTextField
//cb.addItem(tName.getText());
cb.addItem(new String(tName.getText()));
cb.setSelectedItem(new String(tName.getText()));
}
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
Rest of crash code:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1 at
java.util.ArrayList.elementData(Unknown Source) at
java.util.ArrayList.get(Unknown Source) at
Okno.actionPerformed(Okno.java:339) at
javax.swing.JComboBox.fireActionEvent(Unknown Source) at
javax.swing.JComboBox.contentsChanged(Unknown Source) at
javax.swing.AbstractListModel.fireContentsChanged(Unknown Source) at
javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElementAt(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElement(Unknown Source) at
javax.swing.JComboBox.removeItem(Unknown Source) at
Okno.actionPerformed(Okno.java:328) at
javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at
javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.setPressed(Unknown Source) at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source) at java.awt.Component.processMouseEvent(Unknown Source) at
javax.swing.JComponent.processMouseEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at
java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at
java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Window.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$500(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
Try adding the following modifications...
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
// -1 means that no item is selected
if (z > -1) {
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
// -1 means that no item is selected
if (i > -1) {
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
}
It seems I fixed this.
Now code is like this:
I'm too lazy to rename the var to eng. Please ignore System out.
so:
nazwy = names
oceny = numbers
sOceny = sNumbers
cbLista = cb
tNazwa = tNames
tOceny = tNumbers
//----
else if(s == bComboDelete)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
sOceny.remove(z);
nazwy.remove(z);
cbLista.removeItemAt(z);
System.out.println("Oceny w bloku delete(if)"+oceny.toString());
}
System.out.println("Oceny w bloku delete(poza if)"+oceny.toString());
}
else if(s == cbLista)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
tNazwa.setText(nazwy.get(z));
oceny.clear();
oceny=arrayStringToIntegerArrayList(sOceny.get(z));
tOceny.setText(oceny.toString().substring(1, oceny.toString().length()-1));
System.out.println("Oceny w bloku CB"+oceny.toString());
}
else
{
tNazwa.setText("");
tOceny.setText("");
oceny.clear();
}
}
I have been working on a project and the project is to create a game of Noughts and Crosses. I have already established the groundwork for the game and I'm currently developing it further. However , when I run the program and the AI is chosen to make the first move , I was returned a Java Null pointer exception in this line :
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
Game.Board[a][b] consists of 3x3 Jbuttons. PlayerMark is a string that either can contain "X" or "O".
How to solve this problem?
Where AI method is being called:
public void StartGame()
{
SideAssigner();
State = true;
if ( AIGame == true && FirstTurn ==true)
{
Computer.AI();
}
while ( State = true )
{
WinValidator();
}
}
Message in console box :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Computer.AI(Computer.java:19)
at Game.StartGame(Game.java:179)
at Game$10.actionPerformed(Game.java:739)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Sour
Update :
Here is an example of how each JBUtton's properties are determined:
Button1.setText("");
Button1.setEnabled(false);
Button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( State == true && playerO == true && PlayerGame == true )
{
isEmpty = false;
Button1.setText("O");
// WinValidator
// TurnChecker ??
}
else if ( State == true && playerX == true && PlayerGame == true )
{
isEmpty = false;
Button1.setText("X");
// WinValidator
// TurnChecker
}
else if ( State == true && computerO == true && AIGame == true)
{
isEmpty = false;
// Call Computer Class
// WinValidator
// TurnChecker
}
else if ( State == true && computerX == true && AIGame == true)
{
isEmpty = false;
// Call Computer Class
// WinValidator
// TurnChecker
}
}
});
AI Method ( snippet of it otherwise it would be too much to display) :
public static void AI()
{
for(int i=0; i<3; i++ )
{
for (int j=0; j<3; j++)
{
// Diagonal Defensive Strategy
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
{
if( !Game.Board[2][2].getText().equals(Game.ComputerMark) && !Game.Board[2][2].getText().equals(Game.PlayerMark))
{
Game.Board[2][2].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
if(Game.Board[2][2].getText().equals(Game.Board[1][1].getText()) && Game.Board[2][2].equals(Game.PlayerMark))
{
if( Game.Board[0][0].getText().equals(Game.ComputerMark) && !Game.Board[0][0].getText().equals(Game.PlayerMark))
{
Game.Board[0][0].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
{
if( !Game.Board[2][2].getText().equals(Game.ComputerMark) && !Game.Board[2][2].getText().equals(Game.PlayerMark))
{
Game.Board[2][2].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
Here is how to solve a NullPointerException. You should learn how to solve these problems yourself as you will get a lot of them:
Look at your stack trace:
at Computer.AI(Computer.java:19)
at Game.StartGame(Game.java:179)
Find the line at the top of the trace:
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
If you can't see the error, split the line up into smaller statements:
tmp = Game.Board[0];
tmp2 = tmp1[0];
tmp3 = Game.Board[1];
tmp4 = tmp3[1];
etc, etc - I am not sure what the types are, but you will know that.
Run it again and see where it falls over. The line number will now tell you exactly which statement has failed. The reference in that statement must be null.
If you don't know why the reference is null, follow the logic back and repeat the changes above.
You could also learn to use the debugger in an IDE such as Eclipse.
I have an application with an xml like this :
<root>
<info>
.....
</info>
<type>
<object_type>..</object_type>
<prop>
<data>
.... . ..
</prop>
<param>
....
</param>
<param>
....
</param>
<param>
....
</param>
etc
All this data is parsed from XML and now I the user should be able to edit the data.
So I have implemented a method for updating the params:
but its giving me an exception due to wrongly written Xpath statement :
javax.xml.xpath.XPathExpressionException
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.compile(Unknown Source)
at xmleditor.service.XMLEditorService.updateParameters(XMLEditorService.java:96)
at xmleditor.gui.XmlEditorMain$5$1.tableChanged(XmlEditorMain.java:364)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableCellUpdated(Unknown Source)
at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)
at javax.swing.JTable.setValueAt(Unknown Source)
at javax.swing.JTable.editingStopped(Unknown Source)
at javax.swing.AbstractCellEditor.fireEditingStopped(Unknown Source)
at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(Unknown Source)
at javax.swing.DefaultCellEditor.stopCellEditing(Unknown Source)
at javax.swing.JTable$GenericEditor.stopCellEditing(Unknown Source)
at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(Unknown Source)
at javax.swing.JTextField.fireActionPerformed(Unknown Source)
at javax.swing.JTextField.postActionEvent(Unknown Source)
at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: javax.xml.transform.TransformerException: Ett platssteg förväntades efter token '/' eller '//'.
at com.sun.org.apache.xpath.internal.compiler.XPathParser.error(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.RelativeLocationPath(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.LocationPath(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.PathExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.UnionExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.UnaryExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.MultiplicativeExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.AdditiveExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.RelationalExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.EqualityExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.AndExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.OrExpr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.Expr(Unknown Source)
at com.sun.org.apache.xpath.internal.compiler.XPathParser.initXPath(Unknown Source)
at com.sun.org.apache.xpath.internal.XPath.<init>(Unknown Source)
at com.sun.org.apache.xpath.internal.XPath.<init>(Unknown Source)
... 41 more
So what I have try to do is the get the rowCount from the table that the user edit and store it in an int x. Then I have stored the columnName in an String columnName. And I am trying to use this variables in my xpath expression to find the perfect location depending on the ObjectType the user has selected. and update and save it in the xml file. But somehow it seems that my xpath expression is wrong or that the transformer cannt read it somehow. since I also get this one :
Caused by: javax.xml.transform.TransformerException
this is my java code:
// Update the parameters
public void updateParameters(String columnName, Object data, int x,
Type type) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
File file = new File("xmlFiles/CoreDatamodel.xml");
System.out.println("Incoming String value : " + data);
System.out.println("Index value : " + x);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
Node node = (Node) xPath.compile(
"//OBJECT_TYPE[text() = '" + type.getObjectType()
+ "']/following-sibling::param/[position()='" + x
+ "']/'" + columnName + "'").evaluate(xmlDocument,
XPathConstants.NODESET);
// Set new NodeValue
node.setNodeValue(data.toString());
// Save the new updates
try {
save(file, xmlDocument);
} catch (Exception e) {
e.printStackTrace();
}
}
// Method for saving the new updated data.
public void save(File file, Document doc) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
// Holds the old document
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String s = writer.toString();
System.out.println(s);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(s);
bufferedWriter.flush();
bufferedWriter.close();
}
how to fix this?
Update :
This code solves the problem but the node is null so the expression is working.
Node node = (Node) xPath.compile(
"//OBJECT_TYPE[text() = '" + type.getObjectType()
+ "']/following-sibling::param[position()= '" + x
+ "']/" + columnName + "").evaluate(xmlDocument,
XPathConstants.NODE);
So far, I see two problems:
param*
A name test in XPath doesn't work the same way as a glob. Broadly speaking, you either match a name completely, or you use * to match any node of the principal node type for that axis (normally an element).
As such, param* does not match things like param, param0, param-something-else, it's just an invalid expression.
/[
You can't have a predicate filtering nothing. A nodeset must be matched by a nodetest first, then filtered by a predicate.
There are two possibilities here:
The / is superfluous and must be removed (if you are trying to use the predicate to filter the nodeset returned by the expression preceding the /).
A nodetest must be inserted after the /, (if you are trying to filter the children or descendants of nodes within that nodeset).
I'm trying to make a game with Java and in the game, the object that moves side ways called 'Pinko' is supposed to fire small objects called 'pellets' when the up or down arrow keys are pressed. It successfully compiles and runs, but every time I press the up or down arrow key, I get an error saying:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Pinko.move(Pinko.java:75)
at A2JPanel.actionPerformed(A2JPanel.java:102)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
There are seven classes: Application, Constants, JFrame, JPanel, Lovely, Pellet and Pinko.
My code in the move method in Pinko class looks like:
public void move(){
area.x -= speed;
if(area.x <= PINKO_MOVE_AREA_LHS || area.x >= PINKO_MOVE_AREA_RHS){
speed = -speed;
}
if( pelletsFired > 0 ){
for (int i = 0; i < pelletsFired; i++){
pellets[i].move();
}
}
}
And the ActionPerformed method in JPanel class looks like:
public void actionPerformed(ActionEvent e){
createLovely();
if(numberOfLovelies > 0){
for (int i = 0; i < numberOfLovelies; i++){
lovelies[i].move();
}
}
pinko.move();
repaint();
}
I have no idea why I keep getting the error mentioned above.
Is there something wrong with the for loop in the move() method in Pinko class??
Any help will be much appreciated...
I would bet the NullPointerException happens here:
pellets[i].move();
Have you tried verifying that:
The Array is initialized
The index referenced contains an instance of what I suppose will be your Pellet class
If you are using an IDE then try to use the debugger to help you understand what is going wrong in your code. Otherwise a few traces can help you debug and nail the problem : Here is the updated code you can try :
public void actionPerformed(ActionEvent e){
createLovely();
if(numberOfLovelies > 0){
for (int i = 0; i < numberOfLovelies; i++){
if(lovelies[i] != null )
lovelies[i].move();
else
System.out.println("ERROR: Null lovelies found at an index : " + i);
}
}
if(pinko != null)
pinko.move();
else {
System.out.println("OOPS pinko is null");
}
repaint();
}
I have a list:
JList characterList = new JList(characterListModel);
characterListModel = new DefaultListModel();
String myCharacters[]={"Dean Winchester","Sam Winchester",
"Bobby Singer","Castiel"};
for (String myCharacter : myCharacters) {
((DefaultListModel) characterList.getModel()).addElement(myCharacter);
}
And I've written a method, in a seperate class, to remove a character at a selected index:
public void removeCharacter() {
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
int idx = characterList.getSelectedIndex(); //<---line 62
int size = characterListModel.getSize();
characterListModel.remove(idx);
if (size == 0) {
//do nothing
} else {
if (idx == characterListModel.getSize()) {
idx--;
}
characterList.setSelectedIndex(idx);
characterList.ensureIndexIsVisible(idx);
}
}
However when I run it with my button, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.detica.LarpDB.Controller.Controller.removeCharacter(Controller.java:62)
at com.detica.LarpDB.view.PlayerContentPane$3.actionPerformed(PlayerContentPane.java:94)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
A lot of the issues I've seen googling this, stem from the line: DefaultListModel characterListModel = ....
And the issue they have is that their creating a new instance of the object, now I''m only new to this whole Java thing, but this shouldn't be an issue with me, as I've not made anythign new, I've just been specific about which object this is.
Please could someone help me untangle myself?
Those 2 lines can create a lot of problems:
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
If any of the chained methods return null (for whatever reason) the line will throw a NullPointerException.
I suggest you break them down in several lines and check the value of each call to see where you get the null from.
EDIT
Just realised that line 62 is int idx = characterList.getSelectedIndex();. It means that characterList is null.
If it's failing on the line that you indicated is line 62, then the only object referenced on that line, and therefore the only thing that could be null, is characterList. This implies that your getCharacterList function is returning null. (If the error was inside the getSelectedIndex function, then you would have another line in your stack trace.)
As you didn't post the getCharacterList function, I can't say much more. But you should take a look at that function and see under what circumstances it could return null.