我在Kotlin(Android)的findviewbyid函数中遇到了空指针异常。

huangapple go评论67阅读模式
英文:

I am facing a null pointer exception in findviewbyid function for kotlin(Android)

问题

Android Studio的Logcat显示:“Caused by: java.lang.NullPointerException: findViewById(R.id.rvMaps) must not be null

安装在Android模拟器或物理设备上的应用程序由于空指针异常而无法打开。

我已经尝试了几天,但无法找到解决方案。

请帮助我。谢谢!

MainActivity.kt中的代码如下:

package eu.tutorials.mymaps

import androidx.appcompat.app.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?) {

        rvMaps = findViewById(R.id.rvMaps)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val userMaps = generateSampleData()
        // 在RecyclerView上设置布局管理器
        rvMaps.layoutManager = LinearLayoutManager(this)
        // 在RecyclerView上设置适配器
        rvMaps.adapter = MapsAdapter(this, userMaps)
    }

    private fun generateSampleData(): List<UserMap> {
        return listOf(
            UserMap(
                "Memories from University",
                listOf(
                    Place("Branner Hall", "Stanford最好的宿舍", 37.426, -122.163),
                    Place("Gates CS building", "在这个地下室度过了很多个漫长的夜晚", 37.430, -122.173),
                    Place("Pinkberry", "与妻子的第一次约会", 37.444, -122.170)
                )
            ),
            UserMap("一月度假计划!",
                listOf(
                    Place("东京", "过夜转机", 35.67, 139.65),
                    Place("兰契", "探亲+婚礼!", 23.34, 85.31),
                    Place("新加坡", "受“疯狂的亚洲富人”启发", 1.35, 103.82)
                )),
            UserMap("新加坡旅行行程",
                listOf(
                    Place("滨海湾花园", "令人惊叹的城市自然公园", 1.282, 103.864),
                    Place("裕廊鸟公园", "适合家庭的鸟类品种众多的公园", 1.319, 103.706),
                    Place("圣淘沙", "度假胜地,可欣赏全景", 1.249, 103.830),
                    Place("植物园", "世界上最伟大的热带花园之一", 1.3138, 103.8159)
                )
            ),
            UserMap("我在中西部最喜欢的地方",
                listOf(
                    Place("芝加哥", "中西部的城市中心,“风城”", 41.878, -87.630),
                    Place("密歇根罗切斯特", "底特律市郊的最佳地方", 42.681, -83.134),
                    Place("马基诺城", "进入上半岛的入口", 45.777, -84.727),
                    Place("密歇根州立大学", "斯巴达人的家园", 42.701, -84.482),
                    Place("密歇根大学", "狼党的家园", 42.278, -83.738)
                )
            ),
            UserMap("要尝试的餐馆",
                listOf(
                    Place("Champ's Diner", "布鲁克林的复古餐厅", 40.709, -73.941),
                    Place("Althea", "芝加哥高档餐厅,享有惊人的美景", 41.895, -87.625),
                    Place("Shizen", "旧金山的优雅寿司店", 37.768, -122.422),
                    Place("Citizen Eatery", "奥斯汀的明亮咖啡馆,有一只粉红兔子", 30.322, -97.739),
                    Place("Kati Thai", "正宗波特兰泰国菜,用爱心制作", 45.505, -122.635)
                )
            )
        )
    }

}

我不知道这个问题的确切原因,但我尝试通过在MainActivity.kt中使用其ID访问rvMaps RecyclerView,导致应用程序崩溃并引发了空指针异常。

英文:

Logcat of Android studio states that "Caused by: java.lang.NullPointerException: findViewById(R.id.rvMaps) must not be null"

App installed on android emulator or physical device doesn't open up due to nullpointer
exception.

Been trying to find the solution from a few days but wasn't able to find on.

Help me out with this.
Thanks!

Code in MainActivity.kt is:

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

I dont know the exact reason of this issue but I tried to access the rvMaps recycler view
through its id in the MainActivity.kt which threw a nullpointerexception crashing the app.

答案1

得分: 1

rvMaps = findViewById(R.id.rvMaps)

将以下代码写入:

setContentView(R.layout.activity_main)
code

override fun onCreate(savedInstanceState: Bundle?) {

//rvMaps = findViewById(R.id.rvMaps) //不应该在这里写
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvMaps = findViewById(R.id.rvMaps) //应该在setcontentview下面
val userMaps = generateSampleData()
// 在循环视图上设置布局管理器
rvMaps.layoutManager = LinearLayoutManager(this)
// 在循环视图上设置适配器
rvMaps.adapter = MapsAdapter(this, userMaps)

}

英文:
rvMaps = findViewById(R.id.rvMaps)

>write this code below

setContentView(R.layout.activity_main)

code

override fun onCreate(savedInstanceState: Bundle?) {
//rvMaps = findViewById(R.id.rvMaps) //you can&#39;t write here
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvMaps = findViewById(R.id.rvMaps) //it should be below setcontentview
val userMaps = generateSampleData()
// Set layout manager on the recycler view
rvMaps.layoutManager = LinearLayoutManager(this)
// Set adapter on the recycler view
rvMaps.adapter = MapsAdapter(this, userMaps)
}

huangapple
  • 本文由 发表于 2023年2月14日 22:09:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定