0

I have a FirebaseRecyclerAdapter which is used for showing a list of chats. Now it shows all chats and I want it to show only chats which contain current firebase user id in the "users" array:

enter image description here

  mFirebaseDatabaseReference = FirebaseDatabase.getInstance().reference

    val parser = SnapshotParser<ChatModel> { dataSnapshot ->
            val chat = dataSnapshot.getValue(ChatModel::class.java)
            if (chat != null) {
                chat.id = dataSnapshot.key
            }
            chat
        }

    val chatsRef = mFirebaseDatabaseReference.child(ChatActivity.ROOMS_CHILD)
    val options = FirebaseRecyclerOptions.Builder<ChatModel>()
            .setQuery(chatsRef, parser)
            .build()

    mFirebaseAdapter = object : FirebaseRecyclerAdapter<ChatModel, ChatViewHolder>(options) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
            val inflater = LayoutInflater.from(parent.context)
            val viewHolder = ChatViewHolder(inflater.inflate(R.layout.item_chat, parent, false))
            return viewHolder
        }

        override fun onBindViewHolder(viewHolder: ChatViewHolder,
                                      position: Int,
                                      chatItem: ChatModel) {
        }
    }

I had an idea to filter data inside SnapshotParser this way:

val parser = SnapshotParser<ChatModel> { dataSnapshot ->
val chat = dataSnapshot.getValue(ChatModel::class.java)
if (chat != null && chat.users.contains(mFirebaseUser?.uid)){ // I want to add this condition
    chat.id = dataSnapshot.key
    chat
} else {
    null
}

}

but it causes NPE in one of the firebase classes. What is the best way to filter chats by current user?

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Rainmaker
  • 10,294
  • 9
  • 54
  • 89

1 Answers1

0

This method is annotated with @NonNull so my guess is that your parser is not expected to return a null value.

Two options come to mind:

a) Don't use FirebaseUI-Android. Filtering results would be possible using a regular adapter and, for example, requesting value instead of children and using DiffUtil to calculate changes. But there are other ways to do that too!

b) Restructure your data. You could, for example, have a separate collection for each user which holds the keys of the chats that this user is part of.

There might be other ways to do this but that's what came to mind reading your question. Hope this helps!

marcorei
  • 343
  • 2
  • 17