If I'm using Firebase data-base I can set server-time as below:
user.put("time", ServerValue.TIMESTAMP);
And then update it.
But if I used the same one with FireStore it doesn't succeed, Also I don't need to implement firebase-data-base in my gradle for only this purpose.
I can see that there is ServerTimestamp.class related to FireStore but I don't know how to use it.
Thanks in advance.
According to docs it would be something like this:
#ServerTimestamp Date time;
If null it will have the server-generated timestamp, so you don't need to do set the value for it.
Ref:
Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a #ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.
(https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/ServerTimestamp)
Edit:
Or when working with a map type object directly:
DocumentReference docRef = db.collection("objects").document("some-id");
// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());
Ref:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects
Related
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
I have a small firebase database with a list. How can I get the last inserted value of the list?
The elements of the list have as key a date string, example:
2016_05_29 --> data
2016_05_30 --> data
2016_05_31
2016_06_01
2016_06_02
2016_06_03
2016_06_10
2016_06_11
2016_06_12
2016_06_13
2016_06_14
2016_06_15
2016_06_16
2016_06_17
2016_06_18
2016_06_19 //returned value
2016_06_20
2016_06_21
2016_06_22
2016_06_23 //expected value
I am try to get the last value of this list, so 2016_06_23 but for some reason it returns this 2016_06_19 whatever key/order system I use:
Query dateMaxRef = ref.orderByKey().limitToLast(1); //this returns always 2016_06_19 instead of 2016_06_23
dateMaxRef.addListenerForSingleValueEvent(new ValueEventListener()
....
Any idea?
I faced the same issue and for me the reason was because the query was not using the latest data from firebase and instead relying on internal cache. Using .keepSynced(true) on the query fixed it for me. Below is the sample code -
Query causeListPath = mFirebase.child(PATH_CAUSE_LIST).child(SELECTED_CITY)
.child(SELECTED_COURT_CODE).limitToLast(1);
// If user wants un-cached data, force sync
if (!useCache) causeListPath.keepSynced(true);
causeListPath.addChildEventListener(new ChildEventListener() {
...
});
I am tryign to store the current username in the class and having such a tough time.
This is only part of the code
String usernameNewbet = currentUser.getUsername().toString();
bets.put("EndDate", endDate);
bets.put("EndTime", actualTimeString);
bets.put("Player_Pointer", usernameNewbet);
But when I am trying to save I am getting this error.
You probably created a Pointer column named "Player_Pointer" and tried inserting a String into it. When saving pointers in Parse, you're supposed to provide the actual object, in this case the User itself, to the field, and not the objectId.
In your case, change this:
String usernameNewbet = currentUser.getUsername().toString();
bets.put("Player_Pointer", usernameNewbet);
To this:
bets.put("Player_Pointer", currentUser);
I am using parse.com in one of my app. I can insert/fetch data to/from parse. Everything works fine. But I want use createdAt field to fetch data.
I have two queries.
Fetch records which are created today.
Fetch records which are created before today.
Problem is parse compares createdAt fields using date-time so I can not use new Date() in query parameter. Is there any way to compare createdAt field by date only?
This question is similar to mine. But is there any standard method ?
As I understand you, You need function something like a keyword "like" which is used in Database to check if a substring exists in a column. So, we do have a method in Parse's Android APIs.
For that you need to call whereContains(String key, String substring)
which will add a constraint for finding string values that contain a provided string.
So, you can write something like this:
query.whereContains("createdAt", "25-05-2015");
That'll only retrieve those data which fall on this date and won't include time.
Doc Reference: https://www.parse.com/docs/android/api/#ParseQuery/whereContains
EDIT:
As createdAt column is Date type, It'll accept a Date variable only. In that case above mentioned function won't work. So, achieving that we will have to use whereGreaterThan and whereLessThan. Sample code snippet is:
Date midnight = new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
Date elevenfiftynine = new Date();
elevenfiftynine.setHours(23);
elevenfiftynine.setMinutes(59);
elevenfiftynine.setSeconds(59);
query.whereGreaterThan(Constants.CREATED_AT_KEY, midnight);
query.whereLessThan(Constants.CREATED_AT_KEY, elevenfiftynine);
Reference: https://www.parse.com/questions/android-api-query-to-get-all-objects-created-today
I am a newbie with firebase and trying to use this as the backend for an android app to store data. The format of the data is a key,value pair.
This is the code that I am using to store the data :
Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).push();
ref.setValue(map);
Due to the push reference being used the data is getting stored like this :
-J5upSABqTLJ1Wfu-jFq
12345
id: 12345
name: abcd
Where-as I want the data to be store like this :
12345
id: 12345
name: abcd
I am not entirely sure if the code sample above is the right way to store data. Since I want to be able to update the existing data at a later point in time . Any suggestions ?
EDIT 1: I am thinking I need to use push so that I don't over-write the existing data in the firebase repo.
I have just tried to get the data back using the getValue() method and I can only fetch data which is in MAP
EDIT 2: without using a push() method with my reference I can see that the any previous data is getting overwritten and only the latest information is available. I am wondering if they is a better way to obtain the reference and still maintain the previous information
So it looks like you have your own system of unique ids, in which case you shouldn't need to use the .push method (that is just a helper to get a unique ref for new data). So instead of push you should be able to do:
Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).child("12345");
ref.setValue(map);
Assuming your id is "12345" and url is pointing at the location where you want to store all of your persons.
To update the data without overwriting, your ref would be:
Firebase ref = new Firebase(url).child("12345");
And instead of using .setValue you would want to use ref.updateChildren(updates). You can see how to structure the updates from the example in the docs:
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("first", "Fred");
updates.put("last", "Swanson");
nameRef.updateChildren(updates);