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

喜夏-厌秋 提交于 2019-12-28 07:07:30

问题


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.


回答1:


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



回答2:


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();



回答3:


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)



来源:https://stackoverflow.com/questions/46282759/is-there-a-way-to-store-key-in-class-which-i-cast-from-firebase-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!