简体   繁体   English

Firebase setValue与不同类型的地图

[英]Firebase setValue with Map with different types

To update an object in Firebase, I'm using this code, that transforms my model into a dictionary. 要更新Firebase中的对象,我正在使用此代码将模型转换为字典。

This is the method that does such thing: 这是执行此类操作的方法:

private static Map<String, Object> getPlayerData(Player player) {
    Map<String, Object> data = new HashMap<>();
    data.put(PLAYER_ID_KEY, player.getId());
    data.put(PLAYER_NAME_KEY, player.getFullName());
    data.put(PLAYER_SCORE_KEY, player.getScore());
    data.put(PLAYER_STATUS_KEY, player.getStatus());
    return data;
}

and this is how I use the result, setting it as a value for theFirebaseRef : 这就是我使用结果的方法,将其设置为theFirebaseRef的值:

Map<String, Object> playerData = getPlayerData(userAsPlayer, newPlayerStatus);

theFirebaseRef.setValue(playerData, new Firebase.CompletionListener() {/**irrelevant code**/});

It works, but the PLAYER_SCORE_KEY ends up as a string in Firebase, when it should be an int : 它可以工作,但PLAYER_SCORE_KEY最终在Firebase中作为一个string ,当它应该是一个int

在此输入图像描述

I guess it makes sense because I'm doing a Map and declaring its values are of type Object . 我想它是有道理的,因为我正在做一个Map并声明它的值是Object类型。

Is there a way to make PLAYER_SCORE_KEY be an int when setting the value from a Map<String, Object> ? 有没有办法在从Map<String, Object>设置值时使PLAYER_SCORE_KEYint

Edit: 编辑:

The getter getScore() returns an int : getter getScore()返回一个int

public int getScore() {
     return score;
}

Edit: 编辑:

To clarify, score is stored as a String only when called from my app. 为了澄清,只有从我的应用程序调用时,分数才会存储为字符串。 When either the web/iOS client add/modify a player, they save it as an int. 当web / iOS客户端添加/修改播放器时,它们将其保存为int。 The problem is that Android is the only one not doing so! 问题是Android是唯一一个没有这样做的人!

(Setting my model as a value as done in the Firebase documentation isn't an option because the Firebase property names are ugly and the server guy uses different names for everything...) (将我的模型设置为Firebase文档中的值不是一个选项,因为Firebase属性名称很丑,服务器人员使用不同的名称......)

I believe your problem is your map parameters. 我相信你的问题是你的地图参数。 You probably will need to make two maps, one with parameters (String, Object) like you have, and another of type (Integer, Object) to hold any integer information. 您可能需要制作两个映射,一个包含参数(String,Object),另一个包含类型(Integer,Object)以保存任何整数信息。 Then set the values in Firebase accordingly. 然后相应地设置Firebase中的值。

Otherwise, you might could use Integer.parseInt() on PLAYER_SCORE_KEY to convert it to an integer, then set this value in Firebase directly instead of passing it in the map. 否则,您可以在PLAYER_SCORE_KEY上使用Integer.parseInt()将其转换为整数,然后直接在Firebase中设置此值,而不是在地图中传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM