尝试在 recyclerview kotlin 上的空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)

Posted

技术标签:

【中文标题】尝试在 recyclerview kotlin 上的空对象引用上调用虚拟方法 \'void android.widget.TextView.setText(java.lang.CharSequence)\'【英文标题】:Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference on recyclerview kotlin尝试在 recyclerview kotlin 上的空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)' 【发布时间】:2020-09-28 16:51:55 【问题描述】:

尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”

所以我只学了 3 周的 kotlin 就卡住了

这是我的 MainActivity.kt

package com.go.personalitieslist

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


class MainActivity : AppCompatActivity() 

    private lateinit var rvPersonalities: RecyclerView
    private var list: ArrayList<Personalities> = arrayListOf()
    private lateinit var  listPersonalitiesAdapter: ListPersonalitiesAdapter

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mtoolbar = findViewById<View>(R.id.toolbar) as Toolbar
        setSupportActionBar(mtoolbar)

        rvPersonalities = findViewById(R.id.rv_personalities)
        rvPersonalities.setHasFixedSize(true)

        list.addAll(PersonalitiesData.listData)
        showRecyclerList()

    

    override fun onCreateOptionsMenu(menu: Menu?): Boolean 
        menuInflater.inflate(R.menu.main_menu,menu)
        return super.onCreateOptionsMenu(menu)
    

    override fun onOptionsItemSelected(item: MenuItem): Boolean 
        val id = item.itemId
        val intent = Intent(this, About::class.java)
        when(id)
            R.id.profile-> startActivity(intent)
        

        return super.onOptionsItemSelected(item)
    

    private fun showRecyclerList() 
        rvPersonalities.layoutManager = LinearLayoutManager(this)
        val listPersonalitiesAdapter = ListPersonalitiesAdapter(list)
        rvPersonalities.adapter = listPersonalitiesAdapter
        listPersonalitiesAdapter.setOnItemClickCallback(object : ListPersonalitiesAdapter.OnItemClickCallback 

            override fun onItemClicked(data: Personalities) 

                val detailIntent = Intent(this@MainActivity, DetailPage::class.java).apply 
                    putExtra(DetailPage.EXTRA_NAME,data.name)
                    putExtra(DetailPage.EXTRA_DETAIL,data.detail)
                    putExtra(DetailPage.EXTRA_PHOTO,data.photo)
                
                showSelectedPersonalities(data)
                startActivity(detailIntent)

            
        )

    
    private fun showSelectedPersonalities(personalities: Personalities) 
        Toast.makeText(this, personalities.name, Toast.LENGTH_SHORT).show()
    


这是 ListPersonalitiesAdapter.kt

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.item_row_personalities.view.*


class ListPersonalitiesAdapter(val listPersonalities:ArrayList<Personalities>) : RecyclerView.Adapter<ListPersonalitiesAdapter.ListViewHolder>() 

    private lateinit var onItemClickCallback: OnItemClickCallback


    fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) 
        this.onItemClickCallback = onItemClickCallback
    

    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ListViewHolder 
        val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_row_personalities, viewGroup, false)
        return ListViewHolder(view)
    

    override fun onBindViewHolder(holder: ListViewHolder, position: Int) 
         holder.bind(listPersonalities[position])
         holder.itemView.setOnClickListener()
             onItemClickCallback.onItemClicked(listPersonalities[holder.adapterPosition])
         
    

    /*
    val personalities = listPersonalities[position]
    Glide.with(holder.itemView.context)
    .load(personalities.photo)
    .apply(RequestOptions().override(55, 55))
    .into(holder.imgPhoto)
    holder.tvName.text = personalities.name
    holder.tvDetail.text = personalities.detail
    holder.itemView.setOnClickListener 
        onItemClickCallback.onItemClicked(listPersonalities[holder.adapterPosition])
    

     */

    override fun getItemCount(): Int 
        return listPersonalities.size
    

    class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) 
        fun bind(item : Personalities)
            with(itemView)
                tv_item_name.text = item.name
                tv_item_detail.text = item.detail
                Glide.with(this).load(item.photo).into(img_item_photo)
            
        
    
    //var tvName: TextView = itemView.findViewById(R.id.tv_item_name)
    //        var tvDetail: TextView = itemView.findViewById(R.id.tv_item_detail)
    //        var imgPhoto: ImageView = itemView.findViewById(R.id.img_item_photo)

        interface OnItemClickCallback 
            fun onItemClicked(data: Personalities)
        

这是 DetailPage.kt

class DetailPage : AppCompatActivity()

    companion object 
        val EXTRA_NAME = "extra_name"
        val EXTRA_DETAIL = "extra_detail"
        val EXTRA_PHOTO = "extra_photo"
    


    override fun onCreate(savedInstanceState: Bundle?)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)

        showDetailPersonalities()

    


    private fun showDetailPersonalities()
        tv_item_name.setText(intent.getStringExtra(EXTRA_NAME))
        tv_item_detail.setText(intent.getStringExtra(EXTRA_DETAIL))
        Glide.with(this).load(intent.getIntExtra(EXTRA_PHOTO,0)).into(img_item_photo)
    


这是显示详细信息页面的activity_detail.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_>

    <ScrollView
        android:layout_
        android:layout_
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="vertical" >

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/extra_photo"
                android:layout_
                android:layout_
                android:contentDescription="@string/todo"
                tools:background="@drawable/ic_launcher_background" />

            <TextView
                android:id="@+id/extra_name"
                android:layout_
                android:layout_
                android:layout_marginTop="20dp"
                android:layout_marginBottom="15dp"
                android:fontFamily="sans-serif"
                android:textAlignment="center"
                android:textAppearance="@style/TextAppearance.AppCompat.Display1"
                android:textSize="30sp"
                android:textStyle="bold"
                android:typeface="normal" />

            <TextView
                android:id="@+id/extra_detail"
                android:layout_
                android:layout_
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:fontFamily="sans-serif"
                android:textAlignment="viewStart"
                android:textSize="18sp" />
        </LinearLayout>
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

这是调试器按摩

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.go.personalitieslist, PID: 14854
    java.lang.RuntimeException: Unable to start activity ComponentInfocom.go.personalitieslist/com.go.personalitieslist.DetailPage: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.go.personalitieslist.DetailPage.showDetailPersonalities(DetailPage.kt:29)
        at com.go.personalitieslist.DetailPage.onCreate(DetailPage.kt:23)
        at android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

【问题讨论】:

我认为您活动中的这一行缺少 import kotlinx.android.synthetic.main.activity_log_in.* activity_log_in = name of xml => 【参考方案1】:

您在 DetailPage 活动中的 ID 为 tv_item_nametv_item_name 的 TextView 上设置文本,但您的 activity_detail.xml 中没有带有这些 ID 的 TextView。

您想要做的是调用extra_nameextra_detail

private fun showDetailPersonalities()
    extra_name.setText(intent.getStringExtra(EXTRA_NAME)) //change this
    extra_detail.setText(intent.getStringExtra(EXTRA_DETAIL)) //and this
    Glide.with(this).load(intent.getIntExtra(EXTRA_PHOTO,0)).into(img_item_photo)

【讨论】:

以上是关于尝试在 recyclerview kotlin 上的空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)的主要内容,如果未能解决你的问题,请参考以下文章

Recyclerview 未显示来自 Firebase Kotlin 的数据

使用 Kotlin 在片段中引用 RecyclerView 时出现空指针错误

Kotlin 中的 RecyclerView itemClickListener [关闭]

尝试用kotlin做一个app

在 recyclerview kotlin 上实现搜索的问题

Recyclerview没有显示kotlin [重复]