【问题标题】:FirebaseRecyclerAdapter model returning null valuesFirebaseRecyclerAdapter 模型返回空值
【发布时间】:2021-12-14 01:16:04
【问题描述】:

我正在尝试为我的社交媒体应用上的帖子创建评论系统。在我的数据库中,每个帖子在“cmets”表中都有一个部分,如下所示:

“hypno--######”是社交媒体帖子的标题。它包含评论、发表评论的用户的用户 ID 以及发表评论时的 unixtimestamp。每条评论的标题都是在发布时间之后。

这是评论类

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、注释和时间戳来填充持有者,但是当我设置这些值时,我得到的是空值。尝试连接适配器/firebase 和模型/支架时是否缺少某些东西?

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) { }
});

【问题讨论】:

    标签: android firebase-realtime-database android-recyclerview firebaseui android-viewholder


    【解决方案1】:

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

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

    所以你可以:

    • 要么显示一个帖子的 cmets,而是将适配器基于该帖子。所以:FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196")(真正的钥匙在里面)。
    • 或者您可以显示关于每个帖子的一条信息,例如它的键。

    如果您想通过 FirebaseUI 适配器为所有帖子显示一个平面的 cmets 列表,您还必须在数据库中的所有帖子中存储一个平面的 cmets 列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多