0

I have this code for saving and loading a map of tiles:

public void load(File loadFile) {
    try {
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(loadFile);
        Element root = document.getRootElement();
        for (Object tiles : root.getChildren()) {
            Element e = (Element) tiles;
            int x = Integer.parseInt(e.getAttributeValue("X"));
            int y = Integer.parseInt(e.getAttributeValue("Y"));
            worldTiles[x][y] = new Tile(tile.id, new Vector2f(x
                    * Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT));
        }
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void save(File saveFile) {
    Document document = new Document();
    Element root = new Element("blocks");
    document.setRootElement(root);
    for (int x = 0; x < TILE_WIDTH - 1; x++) {
        for (int y = 0; y < TILE_HEIGHT - 1; y++) {
            Element tiles = new Element("block");
            tiles.setAttribute("x",
                    String.valueOf((int) (worldTiles[x][y].getX())));
            tiles.setAttribute("y",
                    String.valueOf((int) (worldTiles[x][y].getY())));
            tiles.setAttribute("type",
                    String.valueOf(worldTiles[x][y].getType()));
            root.addContent(tiles);
        }

    }
    XMLOutputter output = new XMLOutputter();
    try {
        output.output(document, new FileOutputStream(saveFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I then call the code in my input handler like this:

if(Keyboard.isKeyDown(Keyboard.KEY_F)){
        world.save(new File("save.xml"));
    }

    if(Keyboard.isKeyDown(Keyboard.KEY_G)){
        world.load(new File("save.xml"));
    }

However, I get a nullpointer exception. Honestly, this makes no sense as I'm creating the save file before trying to load it, so that isn't the problem. I have tiles in my worldTile[][] array, so it couldn't throw an error there. Some extra info, the Tile constructor looks like this:

public Tile(int id, Vector2f position)

Any help at all?

1 Answers1

0

This is a good case-in-point for using constants! Have constant:

final String X = "X";
final String Y = "Y";

Then the case of the 'save' with lower-case 'x' and the read with the upper-case 'X' would be avoided....

In other words, 'x' is not the same attribute as 'X'.

Rolf

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Right, makes sense. However, I have never even gotten to the creating a file function, I need help with that! –  Dec 31 '12 at 22:44