返回空值的 FirebaseRecyclerAdapter 模型

FirebaseRecyclerAdapter model returning null values

我正在尝试在我的社交媒体应用程序上为 post 建立一个评论系统。在我的数据库中,每个 post 在“评论”table 中都有一个部分,如下所示:

“hypno--######”是社交媒体的标题post。它包含评论、post编辑评论的用户的用户 ID,以及 post编辑评论时的 unix 时间戳。每条评论都以 post 发表的时间命名。

这是评论class

public class comment {

    public String uID;
    public String comment_t;
    public long unixTimestamp;

    public comment() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }
    public comment(String uID, String comment_t, long unixTimestamp) {
        this.uID = uID;
        this.comment_t = comment_t;
        this.unixTimestamp = unixTimestamp;


    }

    public String getuID() {
        return uID;
    }

    public void setuID(String uID) {
        this.uID = uID;
    }

    public String getComment() {return comment_t;}

    public void setComment() {this.comment_t = comment_t; }

    public long getUnixTimestamp() {
        return unixTimestamp;
    }
}

这是评论适配器:

Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {

    private DatabaseReference mDatabase;
    private static final String TAG = "RecyclerViewAdapter";
    private Context mContext;
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    private static AppCompatActivity unwrap(Context context) {
        while (!(context instanceof Activity) && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
        }

        return (AppCompatActivity) context;
    }

    public Adapter_Comment(@NonNull FirebaseRecyclerOptions<comment> options) {
        super(options);
        //this.mContext = mContext;
    }

    @NonNull
    @Override
    public ViewHolder_com onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
        mDatabase = FirebaseDatabase.getInstance().getReference();

        return new ViewHolder_com(view);
    }

    @Override
    protected void onBindViewHolder(@NonNull ViewHolder_com holder, int position, @NonNull comment model) {
        mDatabase = FirebaseDatabase.getInstance().getReference();
        
        long dv = model.getUnixTimestamp()*-1000;
        Date df = new java.util.Date(dv);
        String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);

        holder.time.setText(vv);
        String com = model.getComment();
        holder.comment_text.setText(com);

        mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists())
                {
                    final String picUrl = snapshot.getValue(String.class);
                    Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) { }
        });

        holder.postPfp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //AppCompatActivity activity = (AppCompatActivity) v.getContext();
                AppCompatActivity activity = unwrap(v.getContext());
                Fragment OtherProfileFragment = new OtherProfileFragment();

                Bundle bundle = new Bundle();
                bundle.putString("key", model.getuID());
                OtherProfileFragment.setArguments(bundle);
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
            }
        });

    }


    public class ViewHolder_com extends RecyclerView.ViewHolder {

        TextView comment_text;
        CircleImageView postPfp;
        TextView time;
        RelativeLayout comment_layout;


        public ViewHolder_com(@NonNull View itemView) {
            super(itemView);

            postPfp = itemView.findViewById(R.id.iv_comment_icon);
            comment_text = itemView.findViewById(R.id.tv_comment_text);
            time = itemView.findViewById(R.id.tv_comment_time);
            comment_layout = itemView.findViewById(R.id.comment_layout);


        }
    }
}

这是评论片段:

public class CommentFragment  extends Fragment {

    private DatabaseReference mDatabase;
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    View view;
    String value;
    RecyclerView recyclerView;
    Query query;
    TextView comment_text;
    long unixTime = System.currentTimeMillis() / 1000L;
    public long globalUnix;
    Button comment_post;
    String comment_string;
    Adapter_Comment adapter;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_comment, container, false);
        value = getArguments().getString("key");
        mDatabase = FirebaseDatabase.getInstance().getReference();
        recyclerView = view.findViewById(R.id.recyclerv_comment);
        comment_text = view.findViewById(R.id.tv_comment_type);
        comment_post = view.findViewById(R.id.btn_comment_post);
        globalUnix = (unixTime * -1);

        comment_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(comment_text.getText().toString() == NULL){
                    Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
                }
                else{
                    
                    comment com = new comment();
                    
                    com.uID = user.getUid();
                    com.comment_t = comment_text.getText().toString();
                    com.unixTimestamp = globalUnix;

                    mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);

                }
            }
        });

        initRecyclerView();
        return view;
    }

    private void initRecyclerView(){
        //Log.d(TAG, "initRecyclerView: init recyclerView");

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();

        FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();

        adapter = new Adapter_Comment(options);
        recyclerView.setAdapter(adapter);
        adapter.startListening();
        adapter.notifyDataSetChanged();

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
}

在适配器内部,我正在使用注释模型来获取 uID、注释和时间戳以填充持有者,但是当我设置这些值时,我得到的是空值。尝试连接 adapter/firebase 和 model/holder 时我是否遗漏了什么?

long dv = model.getUnixTimestamp()*-1000;
    Date df = new java.util.Date(dv);
    String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);

holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);

mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists())
        {
            final String picUrl = snapshot.getValue(String.class);
            Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) { }
});

这里发生的事情太多了,但是...

据我所知,您正在 FirebaseDatabase.getInstance().getReference().child("comments") 上创建一个 FirebaseUI 适配器。 FirebaseUI 适配器显示您传入的节点的直接子节点,因此在您的情况下,它将为 hypno---...196 节点创建一个视图。您正在尝试从那里读取一个 Comment 对象,但直到 JSON.

中的下一级才存在

所以你可以:

  • 要么显示一个 post 的注释,方法是将适配器基于该注释。所以:FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196")(真正的关键在那里)。
  • 或者您可以显示关于每个 post 的一条信息,例如它的密钥。

如果您想通过 FirebaseUI 适配器显示所有 post 的评论列表,您必须在数据库中存储所有 post 的评论列表也是。