我想获取存储在实时数据库中的数据。
有了断点,我可以看到我的dataSnapshot
包含好的值。
然后,我想从dataSnapshot
实例化一个线对象(线类包含x1
,y1
,x2
和y2
字段)。
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (isDrawer()) {
return;
}
Line line = dataSnapshot.getValue(Line.class);
if (line != null) {
Log.i("cc", "Values : " + line.getX1() + " " + line.getX2() + " " + line.getY1() + " " + line.getY2());
addLine(line);
}
}
我的问题是我得到的线对象包含x1 = 0, x2 = 0, y1 = 0, y2 = 0
,而不是与快照相同的坐标。
编辑: 我当前对line的实现是非常基本的:
public class Line {
private float x1;
private float y1;
private float x2;
private float y2;
public Line() {
}
public Line(float x1, float y1, float x2, float y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public Line(Line line) {
this.x1 = line.getX1();
this.x2 = line.getX2();
this.y1 = line.getY1();
this.y2 = line.getY2();
}
public float getX1() {
return x1;
}
public void setX1(float x1) {
this.x1 = x1;
}
public float getY1() {
return y1;
}
public void setY1(float y1) {
this.y1 = y1;
}
public float getX2() {
return x2;
}
public void setX2(float x2) {
this.x2 = x2;
}
public float getY2() {
return y2;
}
public void setY2(float y2) {
this.y2 = y2;
}
我通过以下方式创建数据库引用:
databaseReference = database.getReference("draws/unique_draw");
我这样存储我的数据:
databaseReference.push().setValue(line);
@Alex Mamo Here is a preview of my data (lines)
为什么?
答案 0 :(得分:0)
您需要使用.getChildren()
访问单个项目:
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot: dataSnapshot.getChildren()) {
Line line = dataSnapshot.getValue(Line.class);
if (line != null) {
Log.i("cc", "Values : " + line.getX1() + " " + line.getX2() + " " + line.getY1() + " " + line.getY2());
addLine(line);
}
}
}