I have this code in my Android application, creating a new record in Firebase.
Firebase searchRef = myFirebaseRef.child("searches");
Firebase newPostRef = searchRef.push();
Map<String, String> search = new HashMap<String, String>();
search.put("start", start_address);
newPostRef.setValue(search);
String postId = newPostRef.getKey();
How would I go about inserting the ServerValue.TIMESTAMP into this record?
Use the below code to set the timestamp to a particular node
setValue(ServerValue.TIMESTAMP);
Related
in an Android app I have the following:
notebookRef = FirebaseFirestore.getInstance().collection("Registros");
notebookRef.add(new Lista(title, description, geoPoint, null));
Map<String, Object> value = new HashMap<>();
value.put("timestamp", ServerValue.TIMESTAMP);
notebookRef.add(value);
it go mad because instead of generating a timestamp it write the following in the firebase:
the server should generate its own timestamp: see here and here
what am I doing wrong?
You're incorrectly using the ServerValue.TIMESTAMP from Realtime Database instead of FieldValue.serverTimestamp() for Firestore.
My app will generate a gameKey everytime user logged in and clicked "start game" button. Variable "gameKey" is generated by the following code, and then I will save data under the gameKey. The problem is, whenever I restart my app, the Firebase replaced the whole data tree with a new gameKey generated.
What I would like to do is to generate a new gameKey without overwriting the old data every time when my app runs. It would be so glad if anyone can point out my problem, thanks so much!
final FirebaseDatabase database = FirebaseDatabase.getInstance();
UserId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserId = database.getReference("user").child(UserId);
gameKey = currentUserId.child("gameinfo").push().getKey();
Map<String, Object> game = new HashMap<>();
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
currentUserId.child("gameInfo").updateChildren(game);
Firebase Data:
- user
- 5xGKRXeHgThQy70lduPEp3mosTj1 (UID)
- gameInfo
-LLV0H0ZJwYT5M42Obfb
gameDate: "20180903_232015"
gameType: "HKMJ"
player1name: "peter"
player2name: "jenny"
player3name: "john"
player4name: "wilson"
*This is the gameKey generated: "LLV0H0ZJwYT5M42Obfb"
This is the code after your suggestions:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference currentUserId = database.getReference("user").child(UserId);
currentUserId.setValue(new User(mAuth.getCurrentUser().getEmail(), UserPic));
gameKey = currentUserId.child("gameinfo").push().getKey();
Map<String, Object> game = new HashMap<>();
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
currentUserId.child("gameInfo").child(gameKey).updateChildren(game);
In addition, I tried to replace this line
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
with this line, same result
Game game = new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate );
Appreciate so much for the help!
Firebase ScreenShot
To solve this, please change the following line of code:
currentUserId.child("gameInfo").updateChildren(game);
to
currentUserId.child("gameInfo").child(gameKey).updateChildren(game);
You are basically generating a random key but you aren't using it at all. So you need to pass the gameKey to the child() method as seen in my above code.
Edit: So solve the entire update process, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gameInfoRef = rootRef.child("user").child(uid).child("gameInfo");
String key = gameInfoRef.push().getKey();
Map<String, Object> game = new HashMap<>();
game.put("player1name", tv_player1name.getText().toString());
game.put("player2name", tv_player2name.getText().toString());
game.put("player3name", tv_player3name.getText().toString());
game.put("playerMename", tv_playerMename.getText().toString());
game.put("gameMode", gameMode);
game.put("gameDate", gameDate);
gameInfoRef.child(key).updateChildren(game);
How to give user defined key value in push(), instead of unique value created by push?
This is what am currently doing:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").push().setValue(user);
.push() will create a new item with a unique reference.
You can use updateChildren() to update instead. For example,
User user=new User(Editname.getText().toString(),Editpid.getText().toString(),Editsem.getText().toString());
Map<String, Object> itemValues = user.toMap();
Map<String, Object> childUpdates = new HashMap<>();
// Define the key value here
String username = "yourKeyValueHere";
childUpdates.put("/users/" + username, itemValues);
mDatabase.updateChildren(childUpdates);
You might have to add something similar to the following to your User class.
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("pid", pid);
result.put("sem", sem);
return result;
}
Simplest way is to specify the child key with the child method:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").child(user.pid).setValue(user);
Where I specify user.pid, you can use whatever unique key you use to identify the user (typically when using Firebase Authentication this would be user.getUid()).
This is one way to do it assuming we want to use the User's name as unique key:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
String uniqueKey = user.getName();
//You could use something else for quick reference since two users can have the same name
mDatabaseReference.child("users").child(uniqueKey).push().setValue(user);
I have two nodes from one root and I want to delete the data from both of them in one request. Both sub-nodes has the same key. I tried this:
Firebase firebaseRef = new Firebase(<root_path>);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(<path_to_first_node>, key);
childUpdates.put(<path_to_second_node>, key);
listToRemoveRef.updateChildren(childUpdates, null);
But it removed data from only the first node
It looks like you're using the updateChildren function wrong. What you want to do is this
Firebase firebaseRef = new Firebase(<root_path>);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("<path_to_first_node>" + key, null);
childUpdates.put("<path_to_second_node>" + key, null);
listToRemoveRef.updateChildren(childUpdates);
The second parameter to updateChildren doesn't set the value to null it is an optional completion listener (see documentation). So instead of passing null to it on the last line, you can just omit it.
This is my code for adding records in Firebase. there's variable outside called restauCount valued (int) as 1
public void sendMessage(){
int restauCount = 1;
String identifier ="Restaurant" + restauCount;
Firebase userRef = firebaseRef.child("Caloocan");
EditText nameInput = (EditText) findViewById(R.id.nameTxt);
String name = nameInput.getText().toString();
EditText locInput = (EditText) findViewById(R.id.locationTxt);
String location = locInput.getText().toString();
EditText typeInput = (EditText) findViewById(R.id.typeTxt);
String foodtype = typeInput.getText().toString();
if (!name.equals("")){
Map<String, String> caloocan = new HashMap<String, String>();
caloocan.put("resname", name);
caloocan.put("resloc", location);
caloocan.put("foodtype", foodtype);
Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
users.put(identifier,caloocan);
userRef.setValue(users);
restauCount++;
}
}
When i run the sendessage() again. i will type in the fields and when i click ADD which is the sendMessage it will be added in FireBase , however when i add new data. IT OVERWRITES THE OLD DATA INPUTTED ? HOW CAN I ADD MULTIPLE DATA IN FIREBASE WITHOUT OVERWRITING THE DATA?
restauCount was created to increment the number of Restaurant i inputted,
userRef.push().setValue(users);
The push() method generates a unique key every time a new child is added to the specified Firebase reference
Use
userRef.setValue(users).push();
instead of userRef.setValue(users);
You are using always the same ref
String identifier ="Restaurant" + restauCount;
Firebase userRef = firebaseRef.child("Caloocan");
userRef.setValue(users);
restauCount++;
Check the doc:
Using setValue() in this way overwrites data at the specified location, including any child nodes.
In your case you are overriding the same data for this reason.
You should use the push() method to generate a unique ID every time a new child is added to the specified Firebase reference.
Firebase userRef = firebaseRef.child("Caloocan");
Firebase newRef = userRef.push();
newRef.setValue(users);
//to get the key
String key = newRef.getKey();
you need to update the identifier it stays the same :
int restauCount = 1;
String identifier ="Restaurant" + restauCount;
try something like :
long restauCount = System.currentTimeMillis();
String identifier ="Restaurant" + restauCount;
here each time you send a sendMessage() your identifier got a specific id as the current time in milliseconds + "Restaurant"
if its important to keep int numbers let me know