从Firebase读取数据会返回一个空类

时间:2018-02-15 15:22:01

标签: java android firebase firebase-realtime-database

我在Firebase中保存此类的对象:

public class Route {
    private String uniqueId;
    private long routeTime;
    private float distance;
    private List<Double> lat;
    private List<Double> lon;

    public Route(){}

    public Route (Route r){
        this.uniqueId = r.uniqueId;
        this.routeTime = r.routeTime;
        this.distance = r.distance;
        this.lat = r.lat;
        this.lon = r.lon;
    }

    public Route (String id ,long time, float distance, List<Double> lat,List<Double> lon){
        this.uniqueId=id;
        this.routeTime=time;
        this.distance=distance;
        this.lat=lat;
        this.lon=lon;
    }

    public String getUid(){
        return uniqueId;
    }

    public long getTime(){
        return routeTime;
    }

    public float getDist(){
        return distance;
    }

    public List<Location> getPoints(){
        List<Location> points = new ArrayList<Location>();
        for (int i=0 ;i < this.lon.size() ;i++){
            Location temp = new Location("");
            temp.setLongitude(this.lon.get(i));
            temp.setLatitude(this.lat.get(i));
            points.add(temp);
        }
        return points;
    }

}

这是上传后数据库的示例: https://i.stack.imgur.com/yaNmo.png

以下是我用来保存数据库的路径:

Routes = FirebaseDatabase.getInstance().getReference("Routes");

currUserRoutes = Routes.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
currRoute = currUserRoutes.push();
routeUID = currRoute.getKey();
Route temp = new Route(routeUID,(endDate.getTime()-startDate.getTime())/1000,distance,lat,lon);
        currRoute.setValue(temp); //currRoute is a database reference 

以下是我试图检索它的方法:

DatabaseReference routeRef= FirebaseDatabase.getInstance().getReference().child("Routes").child(userID);
Query a=routeRef.orderByChild("uid").equalTo(routeID);
a.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
             curr_route = singleSnapshot.getValue(Route.class);
        }
    }

当我调试android studio时,在检索数据时会显示正确的值。我的意思是:pressMe

绿色文本包含我期望的正确值,但我在curr_route中获得的值为null,就像他通过默认构造函数like this一样。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

  1. 您需要将Java变量命名为与在数据库中保存它们完全相同的方式,以便Firebase SDK执行的映射非常简单。确保getter和setter也是标准惯例,例如将lat更改为latitude,将getter更改为getLatitude(),将setter更改为setLatitude() 您必须拥有getter和setter < /强>

  2. 我注意到您的latitudelongitude Java变量保存为List<Double>,即使您的数据只是double/float。这可能存在问题。

答案 1 :(得分:0)

您的Route对象应该为要公开的每个属性同时具有getter setter方法。现在你只有一些getter,但是你需要setter才能让Realtime Database SDK在用source("packrat/init.R")从数据库快照中读取时填充这些值。