我无法从Firebase实时数据库中将数据检索到字符串变量中

时间:2020-03-26 16:22:38

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

我的代码如下...我是这一行的新手,所以我们将不胜感激。

@Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerOptions<Contacts> options = new FirebaseRecyclerOptions.Builder<Contacts>().setQuery(ChatsRef, Contacts.class).build();
        FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull final ChatsViewHolder holder, int position, @NonNull Contacts model) {
                final String usersIDs = getRef(position).getKey();
                final String[] retImage = {"default_image"};

                UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists())  {
                            if (dataSnapshot.hasChild("image")) {
                                retImage[0] = dataSnapshot.child("image").getValue().toString();
                                Picasso.get().load(retImage[0]).into(holder.profileImage);
                            }

                            final String retName = dataSnapshot.child("name").getValue().toString();

                            holder.userName.setText(retName);

                            if (dataSnapshot.child("userState").hasChild("state")) {
                                String state = dataSnapshot.child("userState").child("state").getValue().toString();

                                if (state.equals("online")) {
                                    holder.onlineIcon.setVisibility(View.VISIBLE);
                                }
                                else if (state.equals("offline")) {
                                    holder.onlineIcon.setVisibility(View.INVISIBLE);
                                }
                            }

                            else {
                                holder.onlineIcon.setVisibility(View.INVISIBLE);
                            }

// i am having trouble from this portion onwards

                            final String[] retLastMessage = {null};
                            final String[] retLastMessageTime = {null};
                            final String[] retLastMessageDate = {null};

                            RootRef.child("Contacts").child(currentUserID).child(usersIDs).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                                    if (dataSnapshot.hasChild("LastMessage")) {
                                        retLastMessage[0] = dataSnapshot.child("LastMessage").getValue().toString();
                                        retLastMessageTime[0] = dataSnapshot.child("LastMessageTime").getValue().toString();
                                        retLastMessageDate[0] = dataSnapshot.child("LastMessageDate").getValue().toString();
                                    }
                                }

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

                            holder.userLastMessage.setText(retLastMessage[0]);

                            String retLastMessageTimeDate = retLastMessageTime[0] + " " + retLastMessageDate[0];

                            holder.userLastMsgTime.setVisibility(View.VISIBLE);
                            holder.userLastMsgTime.setText(retLastMessageTimeDate);
//upto this I guess


                            holder.itemView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent chatIntent = new Intent(getContext(), ChatActivity.class);
                                    chatIntent.putExtra("visit_user_id", usersIDs);
                                    chatIntent.putExtra("visit_user_name", retName);
                                    chatIntent.putExtra("visit_image", retImage[0]);
                                    startActivity(chatIntent);
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }

            @NonNull
            @Override
            public ChatsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
                return new ChatsViewHolder(view);
            }
        };
        chatsList.setAdapter(adapter);
        adapter.startListening();
    }

app尝试从Firebase检索这些数据时崩溃 请帮忙。我正在使用上面的代码实际获取最终消息和最后消息的时间,以在我的应用程序的聊天片段中显示它。最后一条消息和最后一条消息时间保存在联系人节点中 this is how the database entry looks like

2 个答案:

答案 0 :(得分:0)

as shown in the picture attached to my answer you need to access 1 first, 2 and then 3 or 4.

所以您需要这样做:

    DatabaseReference reference = 
     FirebaseDatabase.getInstance().getReference("Contacts").child("2").child("3");

    // of course you are not going to use 2 and 3 as a child but it's just to illustrate my point

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {



        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

答案 1 :(得分:0)

稍微更改代码后,应用程序运行平稳

更改后的代码为:


                            final String[] retLastMessage = {null};
                            final String[] retLastMessageTime = {null};
                            final String[] retLastMessageDate = {null};

                            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Contacts").child(currentUserID).child(usersIDs);

                            reference.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                    if (dataSnapshot.hasChild("LastMessage")) {
                                        retLastMessage[0] = dataSnapshot.child("LastMessage").getValue().toString();
                                        retLastMessageTime[0] = dataSnapshot.child("LastMessageTime").getValue().toString();
                                        retLastMessageDate[0] = dataSnapshot.child("LastMessageDate").getValue().toString();

                                        holder.userLastMessage.setVisibility(View.VISIBLE);
                                        holder.userLastMessage.setText(retLastMessage[0]);
                                        String retLastMessageTimeDate = retLastMessageTime[0] + " " + retLastMessageDate[0];

                                        holder.userLastMsgTime.setVisibility(View.VISIBLE);
                                        holder.userLastMsgTime.setText(retLastMessageTimeDate);
                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {

                                }
                            });

其余代码保持不变。问题是我在ValueEventListener之后分配值。我不知道正确的原因,但是紫苑在ValueEventLister内部分配值似乎代码可以正常运行。