java - Firebase Rest Api 从我的模型类中读取数据返回 null
问题描述
我正在尝试在 java Restful API 中运行 Get 方法。我尝试将我的模型类命名为类似于我的实时火力库,但这不是问题。
这是我的模型课
private String LightSwitch;
private String DoorSwitch;
// empty COnstructor
public DeviceTest() { }
public DeviceTest(String lightSwitch, String doorSwitch) {
LightSwitch = lightSwitch;
DoorSwitch = doorSwitch;
}
public String getLightSwitch() {
return LightSwitch;
}
public void setLightSwitch(String lightSwitch) {
LightSwitch = lightSwitch;
}
public String getDoorSwitch() {
return DoorSwitch;
}
public void setDoorSwitch(String doorSwitch) {
DoorSwitch = doorSwitch;
}
}
这是我的 readFirebase 方法
public static List<DeviceTest> handleLight() {
FireBaseService fbs = null;
fbs = new FireBaseService();
device = new DeviceTest();
mylist = new ArrayList<>();
DatabaseReference ref = fbs.getDb()
.getReference("/Devices/Lamp");
ref.child("Ambient")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
device = dataSnapshot.getValue(DeviceTest.class);
mylist = new ArrayList<>();
for (DataSnapshot unit : dataSnapshot.getChildren()) {
DeviceTest value = unit.getValue(DeviceTest.class);
mylist.add(value);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//mylist.add(device);
return mylist;
}
这是GET方法
@Path("/devices")
public class DeviceResource {
DeviceService deviceService = new DeviceService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<DeviceTest> getCustomers(){
return FireBaseService.handleLight();
}
解决方案
看起来您正在返回列表,然后再填充数据。
addValueEventListener
是异步的,所以你的方法不要等待它的结果。
onDataChange
当您的数据准备好时将被调用,但可能需要一段时间,因为它必须从网络中的外部源下载它。
看看这个讨论:How to return DataSnapshot value as result of a method?
推荐阅读
- c# - 实体框架不播种实体关系
- java - 使用 LIKE % 的 HQL 查询无法正常工作
- javascript - 使用动态变量访问javascript对象中的第n级嵌套属性
- python - 元组中的 max 函数如何工作?
- r - 基于R中列内因子水平的分层偏好的子集数据框
- vb.net - 如何从访问数据库中获取具有数量的畅销产品并显示在标签上
- php - 参数太少,0 通过
- javascript - React Hooks:setState,什么时候真正生效?
- amazon-web-services - 特定区域的 aws 上出现 504 网关超时错误
- python - 在保留索引的同时对 Pandas DataFrame 中的行进行改组