无法将Firebase中的DataSnapshot解析为java类

时间:2017-06-25 19:33:06

标签: android firebase firebase-realtime-database

尝试将快照从firebase转换为Event类时遇到此问题。创建了Event对象(evento var),但其属性都为null。

FirebaseDatabase.getInstance().getReference("events")
                .orderByChild("event_name").equalTo(event_name)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        Event evento = snapshot.getValue(Event.class);
                        for (Task task:
                             evento.getTasks()) {
                            Log.d("Task name:",task.getName());
                        }


                    }

                    @Override
                    public void onCancelled(DatabaseError error) {
                    }
                });

这是事件类

public class Event {
    private String event_name;
    private List<Task> tasks;

    public Event(String event_name, LinkedList<Task> tasks) {
        this.event_name = event_name;
        this.tasks = tasks;
    }

    public Event() {
    }

    public String getEvent_name() {
        return event_name;
    }

    public void setEvent_name(String event_name) {
        this.event_name = event_name;
    }

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }

}

这是Task类,以防万一

public class Task {
    private String name;
    private Boolean state;
    private String description;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean getState() {
        return state;
    }

    public void setState(Boolean state) {
        this.state = state;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Task(String name, Boolean state, String description) {
        this.name = name;
        this.state = state;
        this.description = description;
    }
    public Task(){

    }
}

1 个答案:

答案 0 :(得分:1)

在不知道JSON的情况下(正如Pat在评论中所说),无法确定。但最有可能的是,你在错误的地方转换类型。

对Firebase数据库执行查询时,可能会有多个结果。因此快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。因此,您的代码需要遍历结果以获取每个匹配事件。

<span>