gpt4 book ai didi

android - Firebase Android ServerValue.Timestamp 映射到 Long

转载 作者:行者123 更新时间:2023-11-29 15:39:22 25 4
gpt4 key购买 nike

我知道这是旧的,我可以在这里找到一些关于这个的热门帖子。但我发誓我仍然被卡住了,我并不是真的理解发布的每个答案,已经 7 个小时了,请善待并给我答案,这让我很痛苦。

为了使答案清晰直接,我决定从其他帖子中发布一个我认为可能是答案的答案,但我只是不知道如何将其应用到我的代码中。

所以,我使用 POJO:

HashMap<String, Object> timestamp = new HashMap<>();

public Reservation(String rid,Map timestamp, String status) {
this.rId = rid;
this.timestamp = timestamp;
this.status = status;
}

public Map getTimestamp() {
return timestamp;
}

这就是我写入数据库的方式:

 private void SendReservation() {
final String key = mDatabaseRes.child("Reservations").push().getKey();

final Reservation reservation = new Reservation(MainActivity.currUser.getUID(),ServerValue.TIMESTAMP,"pending");

mDatabaseRes.child("Reservations").child(key).setValue(reservation, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference reference) {
if (databaseError != null) {

Log.e("Database ERROR", "Failed to write message", databaseError.toException());
} else {
Toast.makeText(getApplicationContext(),
"success"
, Toast.LENGTH_LONG).show();
}
}
});


}

直到现在我成功写入数据库,时间戳还显示时间 14090282xxxx(直到现在似乎是正确的),读取时间戳值时出现错误,类似于快照获取值中的“无法反序列化长映射”:

reservationList.clear();
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
reservationList.add(dsp.getValue(Reservation.class)); //add result into array list

}

好吧,正如我所说,让我在这里选择并展示一个来自 kevin o'neill 的答案,我如何申请我的:这是 link

Param param1;
Param param2;
HashMap<String, Object> timestampCreated;

//required empty constructor
public DataObject(){}

public DataObject(Param param1, Param param2) {
this.param1 = param1;
this.param2 = param2;
HashMap<String, Object> timestampNow = new HashMap<>();
timestampNow.put("timestamp", ServerValue.TIMESTAMP);
}
public HashMap<String, Object> getTimestampCreated(){
return timestampCreated;
}

@Exclude
public long getTimestampCreatedLong(){
return (long)timestampCreated.get("timestamp");
}

这是接受了一些投票的答案,让我困惑的是 timestamnow 和 timestampcreated 之间的联系是什么? ,构造函数也没有像我那样的时间戳。

我需要在我的代码中添加什么才能使其获得正确的结果。

最佳答案

卡了14个小时后,我终于想出了解决办法。

我的灵感来自 here

由于来源没有任何解释,我将根据我的情况在这里重写并进行一些解释。

首先,我删除了类外的所有 serverValue.timeStamp,我还从构造函数中删除了它。

然后我添加这个变量成员 Long creationDate;

并添加公共(public) getter,以便它可以将时间戳写入数据库:

 public java.util.Map<String, String> getCreationDate() {
return ServerValue.TIMESTAMP;
}

最后要做的是添加方法来检索 long 的值

@Exclude
public Long getCreationDateLong() {
return creationDate;
}

就是这样,我测试了它并成功了,我希望它也能对以后的人有所帮助。

关于android - Firebase Android ServerValue.Timestamp 映射到 Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43638860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com