4

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.

KENdi
  • 7,576
  • 2
  • 16
  • 31
user2396640
  • 359
  • 4
  • 24
  • Unless you are willing to use a list to hold that value, or you can create a field for the id and set it to null anytime you are writing to the database(that is if the id field is your major concern) – Clement Osei Tano Sep 18 '17 at 15:16

3 Answers3

8

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

No, there is not. This is the only way you can achieve this, by storing that pushedKey in a string. The return type of getKey() method is String.

String pusedhKey = yorRef.getKey();
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I have the Key when i store the data. but the question is if i need to store it on the DB as well ? Seems odd – user2396640 Sep 18 '17 at 15:18
  • It depends. If you need that key to be stored, then store it. This means that if that key is needed in other parts of your app, then store that key in a separate filed. Don't store data in your database if it is not needed. If you need that key across the whole app, you can store it in an `Intent` or in `SharedPreferences`. – Alex Mamo Sep 18 '17 at 15:21
  • I recommend against duplicating the key in a property of the object. While duplication of data is quite normal in the Firebase Database, this nearby value duplication typically points to something that is better done in code. – Frank van Puffelen Sep 18 '17 at 16:12
  • Thanks @FrankvanPuffelen! – Alex Mamo Sep 18 '17 at 16:15
0

When working with firebase, I prefer to store my data in a hashmap, so I can keep my model class clean, while also able to keep the key.

So for example, in onDataChanged(snap:DataSnapshot)

MyModel m = snap.getValue(MyModel.class); myHashMap.put(snap.key, m)

Btw, HashMap<String, MyModel> myHashMap;

(Excuse the quirky formatting, i'm typing from my phone)

Moses Aprico
  • 1,951
  • 5
  • 30
  • 53