Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase ServerValue.TIMESTAMP in Java data models objects

I'm new to Firebase, and I've been really enjoying it so far. I'm running into a problem; I'm using the FirebaseListAdapter similar to the tutorial outline here: https://github.com/firebase/AndroidChat

To use the FirebaseListAdapter, I need to use data model objects (to get the automatic binding to work nicely). The problem is I also want to keep a timestamp value with that model object, and I want to get the timestamp from the Firebase server.

What I have currently that is NOT working is a class DataModelObject (similar to com.firebase.androidchat.Chat in the demo example) with a constructor like :

DataModelObject(String data1, String data2, Map enQTimeStamp)

which I then try to use like this:

DataModelObject dmo = new DataModelObject ("foo", "bar", ServerValue.TIMESTAMP);
myFirebaseRef.push().setValue(dmo);

This causes a JsonMappingException when I try to run that code. I found a code snippet here :

https://www.firebase.com/blog/2015-02-11-firebase-unique-identifiers.html

But it's worthwhile to note that on line 4 of the Android code example, that will cause a compile time error (as he is trying to put ServerValue.TIMESTAMP into a Map, and TIMESTAMP is a Map itself)

What is the right way to do this and maintain compatibility with FirebaseListAdapter?

like image 914
mkim Avatar asked Apr 16 '16 00:04

mkim


2 Answers

This sounds similar to this question: When making a POJO in Firebase, can you use ServerValue.TIMESTAMP?

When creating POJOs used to store/retrieve data apart from the default empty constructor I usually use a constructor similar to this:

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);
       this.timestampCreated = timestampNow;
}

Be sure to include a getter for the HashMap<> used to store the Timestamp:

public HashMap<String, Object> getTimestampCreated(){
    return timestampCreated;
}

Then use the @Exclude annotation to create a getter that you can use in your code to get the value of the timestamp if you need it. The @Exclude annotation will cause Firebase to ignore this getter and not look for a corresponding property

@Exclude
public long getTimestampCreatedLong(){
    return (long)timestampCreated.get("timestamp");
}
like image 199
Kevin O'Neil Avatar answered Oct 11 '22 08:10

Kevin O'Neil


Here's how I do it

//member variable
Object createdTimestamp;

public YourConstructor(){
    createdTimestamp = ServerValue.TIMESTAMP
}

@Exclude
public long getCreatedTimestampLong(){
    return (long)createdTimestamp;
}
like image 43
MobileMon Avatar answered Oct 11 '22 07:10

MobileMon