Insert a timestamp of data insertion into database - android

I want to add a timestamp of a data entry creation, example:
myRef.child("uid").setValue(data);
//add timestamp to the same path myRef.child("uid").setValue(<timestamp here>)
What would be the best timestamp, so that it will be independent of any time zone? (For example if a user's phone clock is set to the wrong time)
I did see this article from Firebae docs: Timestamp, but can't figure how to use it.

Use the value placeholder firebase.database.ServerValue.TIMESTAMP to update a value with the current clock time on the server at the time of the write, as seen by the server. It's a token value that means nothing on the client but has a special meaning on the server when it's written.

inside Firebase Functions transform the timestamp like so:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

Related

How to notify user that new data is avalable so that they need to refresh?

I'm working on a news app. I fetch data from server directly in JSON format, parse it and show in views. I would like to be able to be able to notfify the use that new data is avaible and they need to refresh instead of automatically updating.
How can I achieve this ?
The simplest way would be to compare the json data string value to the new value from the server. Something like this:
if (currentJSONDataString != newJSONDataString) {
Toast.make(context, “Updates available. Please refresh”, Toast.LENGTH_SHORT).show()
}
The limitation here though is that this only checks to see if your current data differs in any way from the server data. If you had things in your data model such as a datetime field that indicated the last updated at time or something similar you could do a more accurate comparison to check if the current data is before the newer data.

Firebase CompareTo Method

i am trying to use compareTo method based on firebase docs to get how long ago was the database entry created.
https://firebase.google.com/docs/reference/android/com/google/firebase/Timestamp
I am trying to do something like this
var postedAgo = myEntry.dateCreated.compareTo(firebase.database.ServerValue.TIMESTAMP);
myEntry.dateCreated is stored TIMESTAMP, so all i got in my db is numerical value. I hope thats right. But the problem is when i log this it says that compareTo is not a function.
I am obviously doing something wrong, but i cant find almost anything on compareTo beyond the documentation. I wonder if anyone is even using it.
Thanks
Luke
The Firebase Database ServerValue.TIMESTAMP is not an actual value of a timestamp, but a so-called marker value that the server recognized (and then replaces by the current timestamp when writing to the database). Because of this, you cannot use ServerValue.TIMESTAMP in pure client-side operations.
If you want to determine how long ago a node was created, you'd take the timestamp from that node and subtract it from the current timestamp. So if myEntry.dateCreated is a timestamp that was written with ServerValue.TIMESTAMP, you could do:
System.currentTimeMillis() - myEntry.dateCreated

Firebase Query - how to order by a separate field?

I'm working with an Android App that functions as an instant messaging service, and I'm at the point of pulling the message data through into a RecyclerView. I have my Firebase Query object returning all the messages that match the id of the chat that has been loaded, this is done like so:
Query qChatMessages = mDbRefMessages
.orderByChild("messageChat")
.equalTo(mChatId);
So far so good, and this is returning the collection of messages that I expect. The problem is now that, upon passing them to the RecyclerView to be displayed, they come out in the inverse order of how you would typically expect an instant messenger to display, so the messages are actually getting older as you scroll down the chat.
My message nodes in the database all have a messageTimestamp field associated with them, so this is what I would want to sort the data by. The problem is that I don't seem to be able to find a way of ordering the data by any field other than the one that I'm querying on, or getting the results back from Firebase and subsequently ordering them.
Does anyone know how I can work around this, or if there's some Firebase capabilities I'm not aware of?
Thanks in advance,
Mark
The easiest way is to store an extra piece of data in your message nodes which is the epoch time multiplied by -1: this way you can sort on this field and the query will return the right order.
See this post on how to get the epoch time: how to get the number of seconds passed since 1970 for a date value?
However, note that with your current data structure, you will encounter a problem: you will need to sort on this new data (e.g. with .orderByChild("messageCreationTime")) AND filter for a given mChatId (e.g. with equalTo(mChatId)), which is not possible.
So, you would have to re-structure your database (if this is possible) like this:
- messages
- mChatId
- messageUniqueID <- most probably auto-generated by Firebase
- messageTitle: ....
- messageCreationTime: -1525857044
And you would query by:
Query qChatMessages = databaseReference.child("messages").child(mChatId)
.orderByChild("messageCreationTime");

Firebase last action time in specified location

I keep a local copy of a simple database in user's phone. This way the app can be used offline. I want to check with firebase server from time to time and update the local database if there is any change. So I need to know last action (insert, update, delete, etc.) time in a specified location in Firebase database. Is that possible? Or should I implement my own mechanism?
The Firebase Database does not store informations like the timestamp for CRUD operations that are performed. Because of that, you need to store this kind of data yourself with your own mechanism. So, you need to create a new field for each child you want to trace and change the value of the TIMESTAMP every time a action is performed. The best practice is to save your data as a TIMESTAMP like this: ServerValue.TIMESTAMP. Note, that when you are saving the TIMESTAMP, you are saving as a Map and when you are retrieving, you are retrieving it as a long. To set the TIMESTAMP, i recomand you using the following code:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("time", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);
To get you data back, i recomand you using the following method:
public static String getTimeDate(long timeStamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timeStamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
This is possible but you shouldn't
Firebase already has offline capabilities, is very simple to use. Is a 2 steps process:
Set offline capabilities on
Set what you want to keep track ass offline
This is the official documentation
In code this is done something like this:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.keepSynced(true);
There is big temptation to use:
FirebaseDatabase.getInstance().getReference().keepSynced(true);
Trying to keep everything sync by syncing the root reference doesn't work, you have to be specific, at least at 1 level parent.
The syncing when the connection is resumed is automatic, the user has to open the app though, flawless.
Now, if you still insist on doing this, then what you have to do is set ServeValue.TimeStamp
In the same link provided above, you can find how to set the server timestamp, here is the direct reference.
Later you can sort by that timestamp, here is a more detailed answer

solution for SQLite function for time difference without java code

Hey please pay attention to solve this problem I know this could be possible but I am not getting the way ..
I am using sqlite in android to store and manipulate the field as shown below in the figure
Figure http://s16.postimage.org/idc13pxdh/image.png
first_start_time,last_start_time,last_end_time are datetime field in SQLite database
I need to get the difference of last_start_time and last_end_time as mean of function so that I don't need to do it programatically
last_end_time = strftime('%Y-%m-%d %H:%M:%S','now','localtime')
last_start_time= strftime('%Y-%m-%d %H:%M:%S','2012-01-27 02:34:56')
,i,e if my firsttime is =2012-06-15 14:54:33
and Endtime is =2012-06-15 14:54:40
then time diff would be like this =00:00:14;
i want to have such difference time like last_end_time -last_start_time
i also want to use trigger to do use in sqlite data base in android
at the last I need that all my total_expended_time should get summed up like ...
select sum(total_expended_time) from study_result
.. one thing keep in mind the result should be in datetime stamp so that i can reflect it to my UI
Any suggestion will be appreciated

Categories

Resources