Search code examples
androidkotlinnullreferenceexception

Attempt to Invoke virtual method ... on a null object reference


I get a null object reference Exception message everytime I try filter data from Firebase Database and add them into my RecyclerView.

If I pass when(id) { "" -> {...}} everything is fine all Items which I want will be added to the RecyclerView, but if I pass when(id) { else -> {...}} it shows me a null object reference Exception.

- Exception is below the code -

fun fetchVideos(id: String?) {
        if (id == currentFilter) {
            currentFilter = null
            return fetchSubs()
        }

        currentFilter = id
        val uid = auth.uid
        val ref = database.getReference("/content/videos")
        ref.addListenerForSingleValueEvent(object: ValueEventListener {

            @SuppressLint("NotifyDataSetChanged")
            override fun onDataChange(p0: DataSnapshot) {
                val adapter = GroupAdapter<GroupieViewHolder>()
                p0.children.forEach {
                    val video = it.getValue(Video::class.java)

                    when(id) {
                        "" -> {
                            if (video != null && video.publisher_uid != uid) {
                                val user = database.getReference("users/$uid/subscriptions/${video.publisher_uid}")
                                user.addListenerForSingleValueEvent(object : ValueEventListener{
                                    override fun onDataChange(p0: DataSnapshot) {
                                        val sub = p0.getValue(Subscription::class.java) ?: return
                                        if (sub.subscribed == true){
                                            adapter.add(VideoItem(video))
                                        }
                                    }
                                    override fun onCancelled(error: DatabaseError) {

                                    }
                                })
                            }
                        }
                        else -> {
                            if (video != null && video.publisher_uid == id) {
                                adapter.add(VideoItem(video))
                            }
                        }
                    }
                }

                // New Bottom Sheet
                adapter.setOnItemClickListener{ item, view ->
                    val videoItem = item as VideoItem
                    selectedVideo = videoItem.video.video_uid
                    HomeFragment.selectedVideo = selectedVideo
                    updateViewCount()
                    addRecentVideo()
                    showVideoPlayer()
                    createValues()
                }

                try {
                    sub_recyclerview_videos.adapter = adapter
                }catch (e: Exception){
                    Log.d(TAG,"${e.message}")
                }
                adapter.notifyDataSetChanged()
            }
            override fun onCancelled(p0: DatabaseError) {

            }
        })
    }

This is my Exception:

Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference


Solution

  • The Problem was not the adapter or my layout it was actually my class SubItem.

    class SubItem(val channel: Channel) : Item<GroupieViewHolder>() {
        @SuppressLint("ResourceAsColor")
        override fun bind(viewHolder: GroupieViewHolder, position: Int) {
            var selected_position = SubscriptionsFragment.selected_position
            val profileImageUrl =  channel.channel_logo
    
            viewHolder.itemView.sub_item_name.text = channel.channel_name
    
            viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.white)
            viewHolder.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)
    
            val targetImageView = viewHolder.itemView.sub_item_profile
            try {
                Picasso.get().load(profileImageUrl)
                    .placeholder(R.drawable.ic_baseline_account_circle_24)
                    .into(targetImageView)
            }catch (e:Exception){
                Log.d("SubItem","${e.message}")
    //            Toast.makeText(,e.message,Toast.LENGTH_SHORT).show()
            }
    
            /*viewHolder.itemView.sub_item_layout.setOnClickListener {
                selected_position = position
    
                // because I am calling here it doesn't know my recyclerview
                SubscriptionsFragment().fetchVideos(channel.uid) // because I am calling here fetchVideos it blocked another clickListener for the same object
                notifyChanged()
            }*/
    
            checkFilter(viewHolder,position)
            if (SubscriptionsFragment.list[position]){
                viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.colorSecondaryText)
                viewHolder.itemView.sub_item_name.setTextColor(R.color.black)
            }
            else{
                viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.white)
                viewHolder.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)
            }
        }