Firebase realtime DB update child - java

I have a "Users" data structure like this, I want to increment the value of ttl_user by 1 when a user is signed up. And decrement it by 1 when a user has deleted their account.
How can I update the value? Thanks.

In your particular case, it would be as simple as:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = db.child("User");
userRef.child("ttl_user").setValue(ServerValue.increment(1));
And to decrement, simply pass a negative value -1.

Related

How to check if username already exists in firebase Realtime Database

I am trying to check were the users already exists with the same username here is example
Here is my code,
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
Query checkUser = reference.orderByChild("userName").equalTo(userEnteredUserName);
but without the uid it works perfect, but whenever there is uid unable to check the username, Is there is anyway to check username
The query is expecting userName to be a direct field in username node and because userId is not same for everyone you cannot specify a neste path. If you remove the username node and restructure the DB as shown below, the same query should work perfectly:
Users
| // remove [username] node from here
|-userId // userId from Firebase Auth
|
|-userName
|-otherFields
If you want to retain existing structure then you can just check if a node with given username exists:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child("userName");

Firebase insertion overwites instead of appending

I have this database structure in firebase:
Its supposed to collect votes. I have several categories such as president, minister...etc. All people who vie for a "President" seat are listed using their unique keys, and Im trying to collect all voters emails.
This is my code:
public static void insertvote(String userkey, String categ, String candId) {
System.out.println("Returned candidate's userkey or ID: "+userkey);
System.out.println("Returned category: "+categ);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference totalVotesRef = rootRef.child("votes").child(categ).child(candId);
Vote vote = new Vote(userkey);
totalVotesRef.setValue(vote.getVoterEmail());
}
The problem I have is that, when another user logs in and votes, instead of appending their email, its being overwritter to the existing email.
How can I resolve this?
Thanks
Instead of using setValue() at the location to collect emails, which always overwrites existing data, you should look into using push() first, which generates a new child using a random ID. You will want to become familiar with the documentation on working with lists of data, especially appending to a list of data.
totalVotesRef.push().setValue(vote.getVoterEmail())
Each email will appear under that randomly generated child value.

Firebase ensuring a record is not repeated

I have this code:
public static void insertvote(String userkey, String categ, String candId) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference totalVotesRef = rootRef.child("votes").child(categ).child(candId);
Vote vote = new Vote(userkey);
totalVotesRef.push().setValue(vote.getVoterEmail());
}
It is supposed to insert votes into a firebase database, in a votes collections as below:
The idea is to ensure a voter only votes once due to integrity by checking if their email exists in the votes. However, as you can see, a voter can vote twice.
Is there a way I can make a function that checks whether the email exixts in the database, and if it does exist, tell the voter they cant vote twice?
Thanks in advance.
You should use the Firebase Auth UID of the current user as the name of the child key.
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
totalVotesRef.child(uid).setValue(vote.getVoterEmail());
I will give you an idea, think about it. If you use
Shared Preferences, you can put every e-mail address with a boolean flag(True/False - Voted/not). Then, you can call the Shared Preferences and check the boolean value of the flag for every e-mail address. So, if it’s true - don’t allow him to vote.
Wish I helped :)

How to get specific pushedID in Firebase?

I am trying to make app like Instagram with Firebase as a backend, while user adds the comment in any photo, new id is generated by Firebase now I want to add one child(likes) when user click on the like button in this randomly generated comment id but the issue is how to get that particular comment id?
There are two ways in which you can achieve this. So if you want to access a specific comment, you must know something that unique identifies that pcommentll. The first solution would be to store that random id in a variable in the exact moment when you are pushing a new comment to the database using the push() method. To get that id, you can use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String commentId = rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.push()
.getKey();
You can also save that id inside the comment object if you need to use it later. So this is how it looks like in code:
Map<String, Object> map = new HashMap<>();
map.put("noOfLikes", 0);
map.put("commentId", commentId);
rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.child(commentId)
.updateChildren(map);
Once you have this key, you can use it in your reference to update the number of likes. This type of operation is usually done using Firebase transaction and for that I recommend see my answer from this post in which I have explained how to update a score property but same principle aplly in the case of likes.
The second approach would be to create an entire new top level collection like this:
Firebase-rot
|
--- comments
|
--- commentId
|
--- noOfLikes: 1
Using this solution it will be more easy for you to query the database becuase to get the number of likes you'll need only this simple reference:
DatabaseReference noOfLikesRef = rootRef
.child("comments")
.child(commentId)
.child("noOfLikes");
noOfLikesRef.addListenerForSingleValueEvent(/* ... */);
Try this:
Fetch the commentID before storing it like this:
String CommentId = myRef.push().getKey();
Save the ID along with comment data:
myRef.child(CommentId).set(yourValuesHashMap);
Now, when you retrieve the comments, you'll have the ID of each comment and you can use that the insert the likes.

How to retrieve a particular key from firebase? [duplicate]

I am trying to make app like Instagram with Firebase as a backend, while user adds the comment in any photo, new id is generated by Firebase now I want to add one child(likes) when user click on the like button in this randomly generated comment id but the issue is how to get that particular comment id?
There are two ways in which you can achieve this. So if you want to access a specific comment, you must know something that unique identifies that pcommentll. The first solution would be to store that random id in a variable in the exact moment when you are pushing a new comment to the database using the push() method. To get that id, you can use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String commentId = rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.push()
.getKey();
You can also save that id inside the comment object if you need to use it later. So this is how it looks like in code:
Map<String, Object> map = new HashMap<>();
map.put("noOfLikes", 0);
map.put("commentId", commentId);
rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.child(commentId)
.updateChildren(map);
Once you have this key, you can use it in your reference to update the number of likes. This type of operation is usually done using Firebase transaction and for that I recommend see my answer from this post in which I have explained how to update a score property but same principle aplly in the case of likes.
The second approach would be to create an entire new top level collection like this:
Firebase-rot
|
--- comments
|
--- commentId
|
--- noOfLikes: 1
Using this solution it will be more easy for you to query the database becuase to get the number of likes you'll need only this simple reference:
DatabaseReference noOfLikesRef = rootRef
.child("comments")
.child(commentId)
.child("noOfLikes");
noOfLikesRef.addListenerForSingleValueEvent(/* ... */);
Try this:
Fetch the commentID before storing it like this:
String CommentId = myRef.push().getKey();
Save the ID along with comment data:
myRef.child(CommentId).set(yourValuesHashMap);
Now, when you retrieve the comments, you'll have the ID of each comment and you can use that the insert the likes.

Categories