使用“gdx-fireapp”从 Firebase 下载列表返回带有空字段的对象列表

我正在尝试使用gdx-fireapp库在LibGdx应用程序中处理 Firebase 。


我遵循了这里给出的例子。我有“下载列表”示例的问题:


我创建了 POJO“用户”类并成功地在数据库中写入了一个用户......所以数据库包含一个包含 1 个用户的列表,其中填写了所有字段(在数据库控制台中验证)。


现在,当我尝试下载具有确切给定代码的用户列表时,我得到一个包含 1 个用户的列表(OK),所有字段均为 NULL


这是“用户”POJO 类


public class UserPOJO{

  public String username;

  public String email;

  public UserPOJO(){}

  public UserPOJO(String username, String email){

    this.username = username;

    this.email = email;

  }

}

这是检索用户列表的代码:


public static void readUsersJava (){

    GdxFIRDatabase.instance().inReference("users")

            .filter(FilterType.LIMIT_FIRST, 5)

            .readValue(List.class, new DataCallback<List<UserPOJO>>(){

                @MapConversion(UserPOJO.class)

                @Override

                public void onData(List<UserPOJO> list) {

                    Gdx.app.log("Firebase Java", "read users OK");

                }

                @Override

                public void onError(Exception e) {

                    Gdx.app.log("Firebase Java", "read users KO");

                }

            });

}

因为我知道用户的 ID,所以我可以尝试从数据库中读取


    GdxFIRDatabase.instance().inReference("users/Xc4x0IOm...")

            .readValue(UserPOJO.class, new DataCallback<UserPOJO>() {...}

但是这样做,我得到“java.lang.ClassCastException:java.util.HashMap 无法转换为 UserPOJO”。

这可能是字段为空的原因:无法投射...但我找不到如何摆脱这个错误


有人可以帮我吗?


慕工程0101907
浏览 175回答 2
2回答

慕桂英546537

好的,我发现了这个:查询答案是 Hashmap<String, Hashmap<String, String>>所以我不得不:添加一个“order by”子句 -> 使用第一级哈希图(我不知道为什么),这似乎是列表查询所必需的创建我的“用户”类的自定义映射所以代码看起来像这样:(“用户”类没有变化)public static void readUsersJava (){setUsersMapConverter()GdxFIRDatabase.instance().inReference("users")&nbsp; &nbsp; &nbsp; &nbsp; .orderBy(OrderByMode.ORDER_BY_KEY, null)&nbsp; &nbsp; &nbsp; &nbsp; .filter(FilterType.LIMIT_FIRST, 5)&nbsp; &nbsp; &nbsp; &nbsp; .readValue(List.class, new DataCallback<List<UserPOJO>>(){&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; });}和fun setUsersMapConverter(){&nbsp; &nbsp; GdxFIRDatabase.instance().setMapConverter(object : FirebaseMapConverter {&nbsp; &nbsp; &nbsp; &nbsp; override fun <T : Any?> convert(map: MutableMap<String, Any>, wantedType: Class<T>): T {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val element = (map.get(map.keys.first())) as HashMap<String, String>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return UserPOJO(element.get("displayName"), element.get("email")) as T&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Should be inversion of convert (needed only by GWT platform)&nbsp; &nbsp; &nbsp; &nbsp; override fun unConvert(`object`: Any): Map<String, Any>? {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}希望能有所帮助。如果您找到更好的解决方案,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java