首页 > 解决方案 > 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();
    }

这是我的邮递员中的空值

标签: javajsonrestfirebase-realtime-databasepostman

解决方案


看起来您正在返回列表,然后再填充数据。

addValueEventListener是异步的,所以你的方法不要等待它的结果。 onDataChange当您的数据准备好时将被调用,但可能需要一段时间,因为它必须从网络中的外部源下载它。

看看这个讨论:How to return DataSnapshot value as result of a method?


推荐阅读