Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to store Key in class which I cast from Firebase object?

This is my database :

[x] database
-- > [+] students
-----> [+] -KuGacomJymBwkcc7zlU (pushKey)
-----------> Name - Jon
-----------> Age - 21

I have Student.class :

String name;
String age;

public Student(String Name, String Age) {
this.name=Name;
this.age=Age;
}

I read the information from firebase datasnapshot like this:

Student newStudent = DataSnapshot.getValue(Student.class);

When I do this I get the name and the age, but my question if there is a way to store the ID (pushKey) on the Student class without adding a String that will hold it and take another field on the firebase database.

Thank you all.

like image 841
user2396640 Avatar asked Mar 09 '23 01:03

user2396640


1 Answers

I prefer keeping the keys and the values separate, or otherwise passing the DataSnapshots around. But if you want, you can also extract the key (DataSnapshot.getKey()) and set it on a property in your Java class that you @Exclude:

public class Student {
  @Exclude
  public String key;
  public String name;
  public String age;
}

And then:

Student newStudent = snapshot.getValue(Student.class);
newStudent.key = snapshot.getKey();

Related:

  • How to manage firebase database keys?
  • Obtaining the reference and key in Custom Object Firebase Android
like image 99
Frank van Puffelen Avatar answered Mar 10 '23 15:03

Frank van Puffelen