简体   繁体   English

Firebase Android ServerValue.Timestamp 映射到 Long

[英]Firebase Android ServerValue.Timestamp Map to Long

I know this is old and i can find some popular post about this here.我知道这是旧的,我可以在这里找到一些关于这个的热门帖子。 but i swear i am still stuck, i don't really understand every answer posted, it's been 7 hours, please be kind and provide me answer, this is killing me.但我发誓我仍然卡住了,我不太理解发布的每个答案,已经 7 个小时了,请善待并给我答案,这让我很痛苦。

to make the answer is clear and direct, i decided to post one answer from other post that i think might be the answer, but i just don't know how to apply it to my code.为了使答案清晰直接,我决定从其他帖子中发布一个我认为可能是答案的答案,但我只是不知道如何将其应用到我的代码中。

So, i use POJO:所以,我使用 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;
 }

and this is how i write to db:这就是我写给数据库的方式:

 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();
            }
        }
    });


}

until now i successfully write to db, the timestamp also display the time 14090282xxxx (seems correct until now), the error raised when reading the timestamp value, something like "cannot deserialize the long to map" at the snapshot get value:直到现在我成功写入数据库,时间戳也显示时间 14090282xxxx(直到现在似乎是正确的),读取时间戳值时出现错误,类似于快照获取值中的“无法反序列化长映射”:

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

}

Okay, as i said, let me pick and show one answer here from kevin o'neill, how can i apply to mine: here is the 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");
    }

this is accepted answer with some votes, what confuse me is what is the connection between timestamnow and timestampcreated?这是接受了一些投票的答案,让我困惑的是 timestamnow 和 timestampcreated 之间的联系是什么? , also the constructor doesn't have timestamp like the one i have. ,构造函数也没有像我那样的时间戳。

what i need to add to my code to make it get the right result.我需要添加到我的代码中以使其获得正确的结果。

after stuck for 14 hours, i finally came up with solution.卡了14个小时后,我终于想出了解决办法。

i inspired from here我的灵感来自这里

Since the source don't have any explanation, i will rewrite it here according to my case with some explanation.由于来源没有任何解释,我将根据我的情况在此处重写并进行一些解释。

First i remove all my serverValue.timeStamp outside my class, i also remove it from my constructor.首先,我删除了我班级之外的所有serverValue.timeStamp ,我还从我的构造函数中删除了它。

then i add this variable member Long creationDate;然后我添加这个变量成员Long creationDate;

and add the public getter so it can write the timestamp to the DB:并添加公共 getter,以便它可以将时间戳写入数据库:

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

last thing to do is to add the method to retrieve the value as long最后要做的是添加检索值的方法

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

That's it, I tested it and worked, i hope it can help someone later too.就是这样,我测试了它并工作了,我希望它也能帮助以后的人。

The ideea is that when you set the TIMESTAMP in your database, you set it as a map and when you retrieve it, you retrieve it as a Long .这个想法是,当你在你的数据库中设置TIMESTAMP时,你将它设置为一个map ,当你检索它时,你将它检索为一个Long

So in order to get the correct TIMESTAMP you need to put a listener on the correct location and than extract the TIMESTAMP from the dataSnapshot like this:因此,为了获得正确的TIMESTAMP ,您需要将listener器放在正确的位置,而不是像这样从dataSnapshot中提取TIMESTAMP

Long timeStampLong = (Long) dataSnapshot.child("timestamp").getValue();

Than you need to use a method to convert it like this:比你需要使用一种方法来转换它是这样的:

public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}

If you want to get the TIMESTAMP from the object than you need to use in your model, public setters and public getters like this:如果您想从对象中获取TIMESTAMP而不是您需要在模型中使用的时间戳,则public setterspublic getters获取器如下所示:

public void setTimeStamp(Map<String, String> timeStamp) {
    this.timeStamp = timeStamp;
}
public Map<String, String> getTimeStamp() {
    return timeStamp;
}

Hope it helps.希望能帮助到你。

For Kotlin users, the idea is the same.对于 Kotlin 用户来说,想法是一样的。 When you set the TIMESTAMP , you set it as a Map and when you retrieve it, you retrieve it as a long .当您设置TIMESTAMP时,您将其设置为Map ,当您检索它时,您将其检索为long

So in order to get the correct TIMESTAMP you need to attach a listener on the correct location and than extract the TIMESTAMP from the dataSnapshot like this:因此,为了获得正确的TIMESTAMP ,您需要在正确的位置附加一个listener器,而不是像这样从dataSnapshot中提取TIMESTAMP

val timestamp = dataSnapshot.child("timestamp").getValue() as Long

Then you need to use a method to convert it like this:然后你需要使用一种方法来转换它,如下所示:

fun getTimeDate(timeStamp: Long): String? {
    return try {
        val dateFormat: DateFormat = getDateTimeInstance()
        val netDate = Date(timeStamp)
        dateFormat.format(netDate)
    } catch (e: Exception) {
        e.message
    }
}

If you want to get the TIMESTAMP from the object than you need to use in your model, a timestamp field like this:如果您想从对象中获取TIMESTAMP而不是您需要在模型中使用的时间戳,则timestamp字段如下所示:

val timestamp = emptyMap<String, String>()

By far the easiest if you ask me.如果你问我,到目前为止是最简单的。

long serverTime = Timestamp.now().getSeconds();

Can be used anywhere and everywhere.可以随时随地使用。

I used Object type for date(timeStamp) field in model class.我在模型类中将对象类型用于日期(时间戳)字段。 This is enough.这就够了。

public class Post {
    private String message;
    private Object timeStamp; //<<<<<<<<<<<<<<<<<<<<< Object 

    public Post() {
    }

    public Post(String message, Object timeStamp) {
        this.message = message;
        this.timeStamp = timeStamp;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(Object timeStamp) {
        this.timeStamp = timeStamp;
    }
}

When writing to Firebase:写入 Firebase 时:

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference("Posts");

Post newPost = new Post("merhaba", ServerValue.TIMESTAMP);
ref.push().setValue(newPost);

When reading data from Firebase:从 Firebase 读取数据时:

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference("Posts");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        postArrayList.clear();
        for (DataSnapshot data : dataSnapshot.getChildren()){
            Post m = data.getValue(Post.class);
            postArrayList.add(m);
        }
        adapterPost.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

When reading timeStampValue:读取 timeStampValue 时:

Post post = postArrayList.get(position);
String timeStampValue= new SimpleDateFormat("MM/dd/yyyy").format(new Date((long) post.getTimeStamp()));

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

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