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

Android Kotlin中findViewById触发NullPointerException问题求助

解决findViewById(R.id.rvMaps)的空指针异常

核心问题:调用顺序错误

你代码里的关键错误是调用findViewById的时机不对——在加载布局之前就尝试获取View了。Android的Activity生命周期中,必须先调用setContentView(R.layout.activity_main)把布局文件加载到内存,之后才能通过findViewById找到布局里的控件。你现在的代码先执行rvMaps = findViewById(R.id.rvMaps),再调用setContentView,这时候布局还没加载,findViewById返回null,而你用了lateinit var且Kotlin要求这个变量非空,直接触发NullPointerException。

修正后的代码

把findViewById的调用移到setContentView之后即可:

package eu.tutorials.mymaps

import androidx.appcompat.appCompatActivity 
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import eu.tutorials.mymaps.models.Place
import eu.tutorials.mymaps.models.UserMap

class MainActivity : AppCompatActivity() {

    private lateinit var rvMaps: RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 现在布局已加载,可正常获取View
        rvMaps = findViewById(R.id.rvMaps)
    
        val userMaps = generateSampleData()
        rvMaps.layoutManager = LinearLayoutManager(this)
        rvMaps.adapter = MapsAdapter(this, userMaps)
    }
    
    private fun generateSampleData(): List<UserMap> {
        return listOf(
            UserMap(
                "Memories from University",
                listOf(
                    Place("Branner Hall", "Best dorm at Stanford", 37.426, -122.163),
                    Place("Gates CS building", "Many long nights in this basement", 37.430, -122.173),
                    Place("Pinkberry", "First date with my wife", 37.444, -122.170)
                )
            ),
            UserMap("January vacation planning!",
                listOf(
                    Place("Tokyo", "Overnight layover", 35.67, 139.65),
                    Place("Ranchi", "Family visit + wedding!", 23.34, 85.31),
                    Place("Singapore", "Inspired by \"Crazy Rich Asians\"", 1.35, 103.82)
                )),
            UserMap("Singapore travel itinerary",
                listOf(
                    Place("Gardens by the Bay", "Amazing urban nature park", 1.282, 103.864),
                    Place("Jurong Bird Park", "Family-friendly park with many varieties of birds", 1.319, 103.706),
                    Place("Sentosa", "Island resort with panoramic views", 1.249, 103.830),
                    Place("Botanic Gardens", "One of the world's greatest tropical gardens", 1.3138, 103.8159)
                )
            ),
            UserMap("My favorite places in the Midwest",
                listOf(
                    Place("Chicago", "Urban center of the midwest, the \"Windy City\"", 41.878, -87.630),
                    Place("Rochester, Michigan", "The best of Detroit suburbia", 42.681, -83.134),
                    Place("Mackinaw City", "The entrance into the Upper Peninsula", 45.777, -84.727),
                    Place("Michigan State University", "Home to the Spartans", 42.701, -84.482),
                    Place("University of Michigan", "Home to the Wolverines", 42.278, -83.738)
                )
            ),
            UserMap("Restaurants to try",
                listOf(
                    Place("Champ's Diner", "Retro diner in Brooklyn", 40.709, -73.941),
                    Place("Althea", "Chicago upscale dining with an amazing view", 41.895, -87.625),
                    Place("Shizen", "Elegant sushi in San Francisco", 37.768, -122.422),
                    Place("Citizen Eatery", "Bright cafe in Austin with a pink rabbit", 30.322, -97.739),
                    Place("Kati Thai", "Authentic Portland Thai food, served with love", 45.505, -122.635)
                )
            )
        )
    }
}

额外排查点(如果修正后仍报错)

  • 检查activity_main.xml中是否存在ID完全匹配的RecyclerView,注意大小写、下划线不能错,比如不能写成R.id.rvmaps或者R.id.RvMaps
  • 确保布局里的RecyclerView标签是androidx.recyclerview.widget.RecyclerView,不是旧的android.support.v7.widget.RecyclerView或其他自定义View
  • 确认app模块的build.gradle(Module级别)中添加了RecyclerView依赖:
    implementation "androidx.recyclerview:recyclerview:1.3.2"
    
    可以替换为最新版本号,没有这个依赖会导致RecyclerView无法被正确实例化

内容的提问来源于stack exchange,提问作者Vibhor Bhatt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:15:59