I am having trouble retrieving data from Firebase real time database into String Variables

Issue

My code is as below… I am new to this line so any help is appreciated.

@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 is crashing when it tries to retrieve these data from firebase
please help. I am using the above code to actually get the final message and time of last message to display it in chats fragment of my app. the last message and last message time are saved in contacts node
this is how the database entry looks like

Solution

after changing the code a little the app ran smoothly

the changed code is:

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

    }
});

rest of the code remains same. the problem was i was assigning values after the ValueEventListener. i don’t know the proper reason but aster assigning the values inside the ValueEventLister the code seems to run fine.

Answered By – eNeM

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published