【问题标题】:How to retrieve data from Firebase? dataSnapshot has the object but getValue() will return null如何从 Firebase 中检索数据? dataSnapshot 有对象,但 getValue() 将返回 null
【发布时间】:2019-11-23 22:46:37
【问题描述】:

我正在尝试制作一个计划扑克应用程序,但我无法使用数据库中的数据填充 recyclerview。我的 Firebase 数据库如下所示:

错误代码:

public void getAllData(){
        databaseReference = FirebaseDatabase.getInstance().getReference();
        databaseReference.child("groups").addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot iter : dataSnapshot.getChildren()) {
                    Group group = iter.getValue(Group.class); 
                    for (Question question: group.getQuestionList()) {
                        RecyclerItem recyclerItem = new RecyclerItem(
                                question.getQuestionText(),
                                group.getStart_time(),
                                group.getEnd_time());
                        recyclerItemsList.add(recyclerItem);
                    }
                }

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });
    }

Group group = iter.getValue(Group.class); 设置end_timestart_time,但不能设置questions

这是我的 Group.java 文件:

package com.example.planningpokerproject.Model;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.firebase.database.Exclude;
import com.google.firebase.database.PropertyName;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Group implements Parcelable {

    @PropertyName("start_time")
    private String start_time;

    @PropertyName("end_time")
    private String end_time;

    @PropertyName("questions")
    private ArrayList<Question> questions;


    public Group() {
    }

    public Group(String start_time, String end_time, ArrayList<Question> questionList){
        this.start_time = start_time;
        this.end_time = end_time;
        this.questions = questionList;
    }

    protected Group(Parcel in) {
        start_time = in.readString();
        end_time = in.readString();
        questions = in.createTypedArrayList(Question.CREATOR);
    }

    public static final Creator<Group> CREATOR = new Creator<Group>() {
        @Override
        public Group createFromParcel(Parcel in) {
            return new Group(in);
        }

        @Override
        public Group[] newArray(int size) {
            return new Group[size];
        }
    };

    public void setStart_time(String start_time) {

        this.start_time = start_time;
    }

    public void setEnd_time(String end_time) {
        this.end_time = end_time;
    }

    public void setQuestionList(ArrayList<Question> questionList) {
        this.questions = questionList;
    }

    public String getStart_time()
    {
        return this.start_time;
    }

    public String getEnd_time()
    {
        return this.end_time;
    }

    public ArrayList<Question> getQuestionList()
    {
        return this.questions;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Exclude
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("start_time", start_time);
        result.put("end_time", end_time);
        result.put("questions", questions);

        return result;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(start_time);
        dest.writeString(end_time);
        dest.writeTypedList(questions);
    }
}

我的问题是如何使用iter.getValue(Group.class) 检索questions 或者我应该怎么做?

【问题讨论】:

  • 您想从数据库中的每个文档中检索问题数组,还是在用数据填充回收站视图时遇到问题?
  • 我想检索问题。对不起,如果我不够清楚。
  • 只是标题有误导性,请尽量改。就检索而言,您应该能够调用iter.get("questions) 并传入字段名称,这里是问题。这应该会返回您可以使用的该字段中的数据,但是您认为合适
  • 我试过了,但iter 没有get 功能。 iter.getValue().get("questions") 在手表中有效,但在代码中无效。它无法编译,因为 iteriter.getValue() 都没有 get 方法。

标签: java android firebase firebase-realtime-database android-recyclerview


【解决方案1】:

您可以创建对您的集合的引用并在其上调用get() 方法来创建对所有文档的查询。然后,您可以简单地添加OnCompleteListener 并访问通过task : Task&lt;QuerySnapshot&gt; 检索到的文档,如下所示。您现在应该能够在每个文档快照上调用 get() 方法,以获取您首选字段的值(在本例中为“问题”)。该代码在 kotlin 中,但如果您复制粘贴,Android Studio 应该能够将其转换为 java 文件。

val rootRef: FirebaseFirestore = FirebaseFirestore.getInstance()
val collRef: CollectionReference = rootRef.collection("groups")
var questions = arrayListOf<String>()
collRef.get().addOnCompleteListener {task: Task<QuerySnapshot> ->
       if(task.isSuccessful) {
             Log.d(TAG,"Success")
             for(document:DocumentSnapshot in task.result!!) {
                     questions = document.get("questions")) // you may need to add some code here to actually get the questions field's values as an array
             }
             adapter.notifyDataSetChanged() // notify the adapter about the new data
        }
}

请记住,如果您的数据库很大,您应该考虑使用数据分页来请求数据,而不是一次请求所有数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多