Android, help with a simpleframework PersistenceException

旧时模样 提交于 2019-12-06 07:22:55

Okay, so because I have been a firm advocate of how awesome Simple XML really is I thought that I would give you a complete answer to this question and so here it is. Completely working code.

Points.java

// You can make this non private and more complex at will.
public class Points {
    @ElementList(entry = "point", inline = true) public ArrayList<Point> points;
}

Point.java

public class Point {
    private final String id;
    private final HashMap<String, Integer> rssiMap;

    public Point(@Attribute(name = "id") String id, @ElementMap(attribute = true, entry = "rssi", key = "ssid", valueType = Integer.class, inline = true) HashMap<String, Integer> rssiMap) {
        this.id = id;
        this.rssiMap = rssiMap;
    }

    @Attribute(name = "id") 
    public String getId() {
            return id;
    }

    @ElementMap(attribute = true, entry = "rssi", key = "ssid", valueType = Integer.class, inline = true)
    public HashMap<String, Integer> getRssi() {
            return rssiMap;
    }
}

Main.java

public class Main {
    public static void main(String[] args) throws Exception {
        Serializer serial = new Persister();

        // Warning: You will need to make sure that this file exists or change it.
        File file = new File("data/data.xml");
        Points points = serial.read(Points.class, file);
        for(Point point : points.points) {
            System.out.println(point.getId());
            for(Entry<String, Integer> entry : point.getRssi().entrySet()) {
                System.out.println(" " + entry.getKey() + ": " + entry.getValue());
            }
        }
    }
}

And that is all that there is to it. It should easily read in your data. If you are going to trial that code then the only thing that you must make sure of is that the Main function sets the File correctly that you are going to read from or you just give the read function the right input.

P.S. I have tested this on my computer so I know that it works. Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!