如何处理我的数据模型类以将Firebase Firestore数据导入recyclerView? [英] How do I handle my data model class to get Firebase Firestore data into recyclerView?

查看:44
本文介绍了如何处理我的数据模型类以将Firebase Firestore数据导入recyclerView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的Firestore数据库:

I have a Firestore database like this:

我想访问每个不同的症状数据,即"Anxiety_data"及其由时间戳组成的子项,然后访问字典,然后使用 FirebaseUI将它们放入 RecyclerView 中.代码> FirebaseRecyclerViewAdapter

I want to access each of the different symptom data's i.e. "Anxiety_data" and its children which consists of timestamps, and then a dictionary, and place them into a RecyclerView using FirebaseUI FirebaseRecyclerViewAdapter

我有这个模型课:

  public class EntryDataModel {
private String timestamp, symptom, severity, comment;

public EntryDataModel() {}

public EntryDataModel(String timestamp, String symptom, String severity, String comment) {
    this.timestamp = timestamp;
    this.symptom = symptom;
    this.severity = severity;
    this.comment = comment;
}

public String getTimestamp() {return timestamp;}
public String getSymptom() {return symptom;}
public String getSeverity() {return severity;}
public String getComment() {return comment;}

}

这是我的 Query :

Query query = db.collection("users").document(user_id).collection("symptom_data");

这是 Firebase RecyclerView适配器:

void fireStoreRecyclerAdapterSetup() {

    FirestoreRecyclerOptions<EntryDataModel> options = new FirestoreRecyclerOptions.Builder<EntryDataModel>()
            .setQuery(query, EntryDataModel.class)
            .build();

    FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<EntryDataModel, EntryDataHolder>(options) {
        @Override
        public void onBindViewHolder(EntryDataHolder holder, int position, EntryDataModel model) {
            // Bind the Chat object to the ChatHolder
            // ...

           System.out.println("Query: " + query.toString());

        }

        @Override
        public EntryDataHolder onCreateViewHolder(ViewGroup group, int i) {
            // Create a new instance of the ViewHolder, in this case we are using a custom
            // layout called R.layout.message for each item
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.entry_data_recyclerview_item, group, false);

            return new EntryDataHolder(view);
        }
    };

    recyclerView.setAdapter(adapter);
    adapter.startListening();

}

}

我不确定应该如何设置,以便从每个症状数据字段中获取所有Timestamp数组,并将它们全部合并在一个列表中,该列表可用于 recyclerView .

I am not sure how I should set this up so that I take all the Timestamp arrays from each of the symptom data fields, and have them all together in a list that I can use for the recyclerView.

也许我不能使用FirebaseUI Recycler适配器,或者我需要首先遍历每个不同的症状字段并构建+附加列表?希望我清楚我想做什么.谢谢.

Maybe I cannot use FirebaseUI Recycler adapter, or I need to iterate through each different symptom field first and build + append a list? Hopefully I am clear in what I would like to do Thank you.

我已经在iOS上完成了,这是我想要的结果:

I have done it on iOS, This is the result that I want:

我已经添加了它,获取了每个文档的名称,然后在for循环中添加了它之后,我现在尝试获取Array值并将其添加到 EntryDataModel 列表,那么我可以使用自己的适配器:

I have added this, getting the names of each individual document, and then once I have that in a for loop I am now trying to get the Array values and add that to an EntryDataModel list, then I can use my own adapter:

这有效,我从每个文档中获取了我需要的数据.现在,我只需要能够遍历字段和时间戳,并使用我的模型来创建列表.我怎样才能做到这一点? Log.d("example","DocumentSnapshot data:" + document.getData()); 会打印: D/example:DocumentSnapshot数据:{1558879769 = {severity = Mild,症状=焦虑,评论=工作中的轻度焦虑.,时间戳= 1558879769},1558879745 = {严重程度=轻度,症状=焦虑,评论=感觉放松地看电视.,时间戳= 1558879745},1558879710 = {严重度=中度,症状=焦虑,comment =正在alk猫.,时间戳= 1558879710},1558879827 = {severity =中度,症状=焦虑,comment =带猫去散步.,timestamp = 1558879827},1558888729 = {severity =轻度,symptom =焦虑,comment =猫厌倦了走路.,timestamp = 1558888729}} 现在,我只需要获取每个timestamp数组并将它们添加到单独的列表中,然后我就可以对每个文档进行此操作并获得完整的所有时间戳数组的列表.

This works, I get the data I need, from each Document. Now I just need to be able to Iterate over the fields and timestamps, and use my model to create a list. How can I do that? Log.d("example", "DocumentSnapshot data: " + document.getData()); this prints: D/example: DocumentSnapshot data: {1558879769={severity=Mild, symptom=Anxiety, comment=Mild anxiety at work., timestamp=1558879769}, 1558879745={severity=Mild, symptom=Anxiety, comment=Feeling relaxed watching TV., timestamp=1558879745}, 1558879710={severity=Moderate, symptom=Anxiety, comment=Walking the cat., timestamp=1558879710}, 1558879827={severity=Moderate, symptom=Anxiety, comment=Taking the cat for a walk., timestamp=1558879827}, 1558888729={severity=Mild, symptom=Anxiety, comment=The cat is fed up with walking., timestamp=1558888729}} Now I just need to get each timestamp array and add them to a seperate list, and i can then do this for each document and have a full list of all the timestamp arrays.

  void getSymptomData() {
     final CollectionReference colRef = db.collection("users").document(user_id).collection("symptom_data");

     colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
         @Override
         public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 List<String> list = new ArrayList<>();
                 for (QueryDocumentSnapshot document : task.getResult()) {
                     list.add(document.getId());
                     DocumentReference docRef = colRef.document(document.getId());
                     docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                         @Override
                         public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                             if (task.isSuccessful()) {
                                 DocumentSnapshot document = task.getResult();
                                 if (document.exists()) {
                                     Log.d("Iteration", "DocumentSnapshot data: " + document.getData());
                                 } else {
                                     Log.d("NoDoc", "No such document");
                                 }
                             } else {
                                 Log.d("Failed", "get failed with ", task.getException());
                             }
                         }
                     });
                 }
                 Log.d("listylist", list.toString());
             } else {
                 Log.d("tag", "Error getting documents: ", task.getException());
             }
         }
     });

}

推荐答案

Firebase SDK可以执行从Firestore文档到Java对象的自动映射,要求文档中的每个字段名称都必须与Java中的属性名称匹配.班级.它没有处理动态字段的机制,例如示例中的时间戳.

The automatic mapping that the Firebase SDK can do from a Firestore document to a Java object, requires that each field name from the document matches a property name in the Java class. It has no mechanism to deal with dynamic fields, such as the timestamps in your example.

因此,您将必须进行自己的转换.为此,您可以使用

So you will have to do your own conversion. For that you can use the public T get (FieldPath fieldPath, Class<T> valueType) or public T get (String field, Class<T> valueType) method, which allow you to get an object from a specific field that you specify. So you will have to loop over the timestamp fields, but after that the Firebase SDK can map the severity, symptom, and timestamp properties to the object.

这篇关于如何处理我的数据模型类以将Firebase Firestore数据导入recyclerView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆