您好我正在使用Firebase实时数据库启动一个新的Android项目。
我的问题是,当我创建新邮件时,我将created_at = ServerValue.TIMESTAMP
设置为Map<String,String>
。当我收到一条消息时,我收到错误解析,告诉我created_at
是long
,我把它放在我的模型中。我的代码如下:
@IgnoreExtraProperties
public class Message implements Serializable
{
@SerializedName("message_id")
@Expose
private String message_id;
@SerializedName("value")
@Expose
private String value;
@SerializedName("sender")
@Expose
private User sender;
@SerializedName("destination")
@Expose
private User destination;
@SerializedName("chatRoom")
@Expose
private ChatRoom chatRoom;
@SerializedName("created_at")
@Expose
private Map<String,String> created_at;
}
我的代码添加新消息:
String idM = databaseReference.push().getKey();
Message m = new Message(idM, message, sender, receiver, chatRoom, ServerValue.TIMESSTAMP);
databaseReference.child(idM).setValue(m);
现在我想将一个默认值设置为created_at,如MySql:
有什么想法吗?
答案 0 :(得分:1)
我用Lucky帮助解决了这个问题。所以解决方案是:
@IgnoreExtraProperties
public class Message implements Serializable {
@SerializedName("message_id")
@Expose
private String message_id;
@SerializedName("value")
@Expose
private String value;
@SerializedName("sender")
@Expose
private User sender;
@SerializedName("destination")
@Expose
private User destination;
@SerializedName("chatRoom")
@Expose
private ChatRoom chatRoom;
@SerializedName("created_at")
@Expose
private HashMap<String, Object> created_at;
public Message() {
}
public Message(String message_id, String value, User sender, User destination, ChatRoom chatRoom) {
this.message_id = message_id;
this.value = value;
this.sender = sender;
this.destination = destination;
this.chatRoom = chatRoom;
this.created_at = new HashMap<>();
this.created_at.put("date", ServerValue.TIMESTAMP);
}
public String getMessage_id() {
return message_id;
}
public void setMessage_id(String message_id) {
this.message_id = message_id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public User getSender() {
return sender;
}
public void setSender(User sender) {
this.sender = sender;
}
public User getDestination() {
return destination;
}
public void setDestination(User destination) {
this.destination = destination;
}
public ChatRoom getChatRoom() {
return chatRoom;
}
public void setChatRoom(ChatRoom chatRoom) {
this.chatRoom = chatRoom;
}
public HashMap<String, Object> getCreated_at() {
if (created_at != null) {
return created_at;
}
//Otherwise make a new object set to ServerValue.TIMESTAMP
HashMap<String, Object> dateCreatedObj = new HashMap<String, Object>();
dateCreatedObj.put("date", ServerValue.TIMESTAMP);
return dateCreatedObj;
}
@Exclude
public long getDateCreatedLong() {
return (long)created_at.get("date");
}
public void setCreated_at(HashMap<String, Object> created_at) {
this.created_at = created_at;
}
}