Reputation:
I want to have my custom unique keys in firebase database as such (User1, User2, User3, User4......Usern).
When I use push();
it generates a long and unclear key that confuses me while sorting.
I also tried child("User1");
but it only saves once in the database with given User1
key. Every time when i want to override Database, it only updates User1 values.
Are there any wiser options to have custom unique keys?
Upvotes: 1
Views: 2807
Reputation: 806
there isn't .. but u can create your own custom key. just like u wanted. but u have to do little more extra work. u have to read the database first.
FirebaseDatabase.getInstance().getReference().child("Users")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> user = (HashMap<String, Object>) dataSnapshot.getValue();
totalUser= user.size();
}
}
now u can add new value with ur custom key
FirebaseDatabase.getInstance().getReference().child("Users").child("user"+totalUsr).setValue(YourValue);
so that the structure will look like this
and so on ....
Upvotes: 1
Reputation: 2396
Instead of using push()
to generate unique keys for your users, use the user
object's uid
to have user nodes in your database. You can get the uid
of the current logged in user by calling the following line :-
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
And then calling the next line to use it as a node in your database :-
mDatabase.child("users").child(uid).child("username").setValue("ABC");
This works great because :-
uid
is unique for each user and is the easiest and most robust way to have and identify user nodes in the database - specially at multiple locations.
uid
of logged in user can be easily obtained from the client Android app using the above line. Therefore, you won't need to specifically save and tally the unique ids on the client. This is recommended not only for simplicity, but also for security.
So, uid
nodes are ideal for user nodes in your database. But, for all other purposes, push()
is still the recommended approach.
Upvotes: 2
Reputation: 2111
You should look into using UUID to help you generate unique keys for your Firebase database without having to use push()
.
import java.util.UUID;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbRef = database.getReference("User1");
// mKey = dbRef.push().getKey();
mKey = UUID.randomUUID().toString();
}
}
Here's a link to another answer addressing generating unique keys.
Upvotes: 3