You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin:Fragment中使用RecyclerView触发空指针异常

Fixing "video_recyclerview must not be null" in Kotlin Fragment RecyclerView

Hey there! Let's break down why you're hitting this IllegalStateException and walk through how to fix it, plus wrap up your incomplete adapter code.

What's Causing the Error?

This error happens because your code is trying to access the video_recyclerview view, but it's null at the point of access. In Kotlin, non-nullable variables can't hold null values, so when the system can't find the view you're referencing, it throws this exception. Common reasons include:

  • A typo or mismatch between the ID in your layout XML and the ID you're using in code
  • Trying to access the view before the fragment's layout is properly inflated
  • Forgetting to use the inflated view instance to find the RecyclerView

Step 1: Verify Your Layout XML

First, double-check your fragment's layout file (e.g., fragment_video.xml) to make sure there's a RecyclerView with the exact ID video_recyclerview. It should look something like this:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/video_recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Pay close attention to spelling, capitalization, and that you're using the correct namespace (androidx.recyclerview.widget.RecyclerView, not the old support library version).

Step 2: Properly Initialize the RecyclerView in Your Fragment

You need to inflate the fragment's layout first, then retrieve the RecyclerView from that inflated view. Here are two reliable ways to do this:

Option 1: Using findViewById (Basic Approach)

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the fragment layout first
    val view = inflater.inflate(R.layout.fragment_video, container, false)
    
    // Get the RecyclerView from the inflated view
    val recyclerView = view.findViewById<RecyclerView>(R.id.video_recyclerview)
    
    // Set required components for RecyclerView
    recyclerView.layoutManager = LinearLayoutManager(context)
    recyclerView.adapter = MainAdapter()
    
    return view
}

View Binding eliminates the risk of ID typos and automatically handles non-null safety. First, enable it in your app-level build.gradle.kts:

android {
    buildFeatures {
        viewBinding = true
    }
}

Then update your Fragment code:

private var _binding: FragmentVideoBinding? = null
// This non-nullable property is only valid between onCreateView and onDestroyView
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentVideoBinding.inflate(inflater, container, false)
    
    // Access RecyclerView directly via binding
    binding.videoRecyclerview.layoutManager = LinearLayoutManager(context)
    binding.videoRecyclerview.adapter = MainAdapter()
    
    return binding.root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null // Clear binding to avoid memory leaks
}

Step 3: Complete Your RecyclerView Adapter

Your current adapter code is missing the critical onCreateViewHolder and onBindViewHolder methods. Here's the full working implementation, assuming you have an item layout (e.g., video_item.xml) with a TextView for the title:

class MainAdapter : RecyclerView.Adapter<CustomViewHolder>() {
    private val videoTitles = listOf("First title", "Second", "3rd", "Moore Title")

    // Return number of items in the list
    override fun getItemCount(): Int = videoTitles.size

    // Create a new ViewHolder for each item
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.video_item, parent, false)
        return CustomViewHolder(itemView)
    }

    // Bind data to the ViewHolder's views
    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        holder.titleTextView.text = videoTitles[position]
    }
}

// Custom ViewHolder class to hold references to item views
class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val titleTextView: TextView = itemView.findViewById(R.id.title_text_view)
}

Make sure the ID title_text_view matches the TextView in your video_item.xml layout.

Final Checks

  • Clean and rebuild your project to ensure all changes are applied
  • Confirm that your Fragment is properly attached to an Activity (if using a single Activity architecture)

内容的提问来源于stack exchange,提问作者Yudha Patria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:37:26