I am struggling with retrieving data from the firebase.
For example, I want to get the first record and get the username & password. How can I get the "key" of the first record?
Here is my code:
private String UserName;
private String Password;
private int Identity;
private DatabaseReference reff = FirebaseDatabase.getInstance().getReference();
public User() {
}
public User(String UserName, String Password, int Identity) {
this.UserName = UserName;
this.Password = Password;
this.Identity = Identity;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName){
this.UserName = UserName;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public int getIdentity() {
return Identity;
}
public void setIdentity(int identity) {
Identity = identity;
}
public void Save(){
reff.child("Users").push().setValue(this);
}
}
User newUser = new User(userName, password, identity);
newUser.Save();
If you want to get the key of the item you are writing, you can see it with:
public void Save(){
DatabaseReference newUserRef = reff.child("Users").push();
newUserRef.setValue(this);
System.out.println(newUserRef.getKey());
}
If you want to find the key while you're reading the users, you can show them with:
DatabaseReference usersRef = reff.child("Users");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.