button.setOnClickListener 使我的应用程序崩溃。科特林 1.3.72

button.setOnClickListener is crashing my app. Kotlin 1.3.72

// 我解决了我的问题感谢您对这个社区的所有帮助。答案贴在下方

所以首先我知道不再支持 kotlin android 扩展。我稍后会更改它。首先,我想确保我的应用程序正常运行并具备所需的功能,然后我会收敛。我对 android studio 有点陌生,所以我有可能错过了一些简单的东西。我做了导入按钮和吐司。

如果我删除按钮 onclick 侦听器,我的应用程序工作正常,所以我认为它一定是罪魁祸首。

主要activity

package com.dispatch.tripsheet

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.table_list_item.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        recyclerViewMovieList.layoutManager = LinearLayoutManager(this)

        recyclerViewMovieList.adapter = TableViewAdapter(movieList)


        // get reference to button
      //  val button1 = findViewById(R.id.button1) as Button

//        button1.setOnClickListener {
//
//            Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
//          tvdone.setBackgroundResource(R.color.green)
//
//        }

//        // get reference to button
//     //   val button2 = findViewById(R.id.button2) as Button
//        // set on-click listener
//        button2.setOnClickListener {
//            // your code to perform when the user clicks on the button
//            Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
//          tvdone.setBackgroundResource(R.color.orange)
//
//        }


        val button1 = findViewById(R.id.button1) as Button
        button1.setOnClickListener {
            Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
            tvdone.setBackgroundResource(R.color.green)
        }
//        button2.setOnClickListener {
//            Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
//            tvdone.setBackgroundResource(R.color.orange)
//        }

//            colour_orange(View view) {
//                // set the color to relative layout
//                relativeLayout.setBackgroundResource(R.color.cool)
//            }
//        });

//        // onClick function for button 2
//        button2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                // set the color to relative layout
//                relativeLayout.setBackgroundResource(R.color.warm)
//            }


        val list : MutableList<String> = ArrayList()
        list.add("Deon")
        list.add("Leon")
        list.add("David")
        list.add("Dick")
        list.add("Jim")
        list.add("Harry")


        val adapter = ArrayAdapter( this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, list)
        val spinner: Spinner = findViewById(R.id.spnDriver)

        spinner.adapter = adapter

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                val item :String = list[p2]

                Toast.makeText(this@MainActivity, "Driver $item selected", Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {
                //empty
            }

            //insert code that activates data pull of tripsheet for driver=


        }

        limitDropDownHeight(spinner)


    }
    fun limitDropDownHeight(spinner: Spinner){



        val popup = Spinner::class.java.getDeclaredField( "mPopup")
        popup.isAccessible = true

        val popupWindow = popup.get(spinner)as ListPopupWindow

        popupWindow.height = (200 * resources.displayMetrics.density).toInt()



    }

     val movieList = ArrayList<MovieModel>().apply {


//         var x: Int = 10
//
//         for (i in 1..x) {
//             println(i)
//
//
//         }

//         var totweight: Int = 40
//         tvTotalweight.setText("Total Weight: " +totweight+ "kg")

        add(MovieModel(190617, 182832, "Jcorp", "378 Begonia 6th street",100))
        add(MovieModel(190617, 182833, "Honda", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Panado", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Gheiters", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "John", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(9190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(190617, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(10, 182832, "Everflu", "365 hellington rogmastreet",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))
        add(MovieModel(10, 182832, "2010", "260",100))


     //need to change from hardcoded text to input
         
     }

    fun weightsum(args: Array<String>) {
        var totweight: Int = 40
        var sum: Int = 0
        //  var input: String

//        for (Int sum : movieList)
//        {
//            System.out.println(sum);
//        }


        tvTotalweight.setText("Total Weight: " +totweight+ "kg")



    }


}



完整 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txtWOrder"
        android:layout_width="160dp"
        android:layout_height="match_parent"
        android:layout_gravity="top"

        android:background="@drawable/table_content_cell_bg"
        android:text="WOrder"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/txtDElNote"
        android:layout_width="190dp"

        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:background="@drawable/table_content_cell_bg"
        android:text="DElNote"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/txtCompany"
        android:layout_width="190dp"

        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:background="@drawable/table_content_cell_bg"
        android:text="Company"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/txtWeight"
        android:layout_width="190dp"
        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:background="@drawable/table_content_cell_bg"
        android:text="Weight"
        android:textSize="18sp" />

<!--    <TextView-->
<!--        android:id="@+id/txtAddress"-->
<!--        android:layout_width="550dp"-->
<!--        android:layout_height="match_parent"-->
<!--        android:layout_gravity="top"-->
<!--        android:background="@drawable/table_content_cell_bg"-->
<!--        android:text="Address"-->
<!--        android:textSize="18sp" />-->


    <!--        android:onClick="ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName))"-->

    <Button
        android:id="@+id/button1"
        android:layout_width="250dp"
        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:background="@drawable/table_content_cell_bg"


        android:text="@string/button1"
        android:textSize="18sp" />




    <Button
        android:id="@+id/button2"
        android:layout_width="250dp"
        android:layout_height="match_parent"
        android:layout_gravity="top"
        android:background="@drawable/table_content_cell_bg"

        android:text="@string/button2"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvdone"
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:background="@drawable/table_content_cell_bg"
        android:text="" />


</LinearLayout>


这个是为了填满我的回收站视图。接下来是我的activtymain.:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    tools:context=".MainActivity"
    android:stretchColumns="*">

    <TableRow
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="1dp"
        android:layout_weight="1"
        android:background="#FFFFFF">

        <TextView
            android:id="@+id/tvHeader"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="Vulcan Steel Trip Sheet: ID NUM TRIPSHEET"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="#000000"
            android:textSize="24sp"
            android:textStyle="bold" />

        <androidx.appcompat.widget.AppCompatSpinner
            android:id="@+id/spnDriver"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@drawable/spinner_bg"
            android:contentDescription="@string/driver"
            android:spinnerMode="dropdown" />


    </TableRow>

<!--    <TableRow-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_margin="1dp"-->
<!--        android:layout_weight="1"-->
<!--        android:id="@+id/headerrow"-->

<!--        android:background="#ffffff">-->

<!--        <TextView-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_weight="1"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_column="0"-->
<!--        android:layout_margin="1dp"-->
<!--        android:background="#FFFFFF"-->
<!--        android:gravity="center"-->
<!--        android:text=" W Order "-->
<!--        android:textAppearance="?android:attr/textAppearanceLarge"-->
<!--        android:textStyle="bold" />-->

<!--    <TextView-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_weight="1"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_column="1"-->
<!--        android:layout_margin="1dp"-->
<!--        android:background="#FFFFFF"-->
<!--        android:gravity="center"-->
<!--        android:text="Del Note "-->
<!--        android:textAppearance="?android:attr/textAppearanceLarge"-->
<!--        android:textStyle="bold" />-->

<!--    <TextView-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_weight="1"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_column="2"-->
<!--        android:layout_margin="1dp"-->
<!--        android:background="#FFFFFF"-->
<!--        android:gravity="center"-->
<!--        android:text="Company"-->
<!--        android:textAppearance="?android:attr/textAppearanceLarge"-->
<!--        android:textStyle="bold" />-->

<!--    <TextView-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_weight="4"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_column="2"-->
<!--        android:layout_margin="1dp"-->
<!--        android:background="#FFFFFF"-->
<!--        android:gravity="center"-->
<!--        android:text="Address"-->
<!--        android:textAppearance="?android:attr/textAppearanceLarge"-->
<!--        android:textStyle="bold" />-->


<!--    <TextView-->
<!--        android:layout_width="0dp"-->
<!--        android:layout_weight="1"-->
<!--        android:layout_height="wrap_content"-->
<!--        android:layout_column="2"-->
<!--        android:layout_margin="1dp"-->
<!--        android:background="#FFFFFF"-->
<!--        android:gravity="center"-->
<!--        android:text="Weight"-->
<!--        android:textAppearance="?android:attr/textAppearanceLarge"-->
<!--        android:textStyle="bold" />-->

<!--    </TableRow>-->

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="570dp"
        android:layout_margin="1dp"

        android:background="#ffffff"
        >

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="570dp"
            android:layout_margin="0dp"



            >


            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerViewMovieList"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:nestedScrollingEnabled="false"
                tools:listitem="@layout/table_list_item" />

        </HorizontalScrollView>


    </TableRow>








    <TableRow
        android:id="@+id/footerow"
        android:background="#ffffff"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvTotaldelv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:text="Total: x Delivery Notes"
            android:textColor="#000000"
            android:textSize="15sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tvTotalweight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Total weight: # xkg"
            android:textColor="#000000"
            android:textSize="15sp" />
    </TableRow>


</TableLayout>

我已经移除吐司和颜色变化,看看是否是这样。但它仍然崩溃了。所以不确定我错过了什么。

Error log: 
2022-03-10 13:42:37.876 20228-20228/com.dispatch.tripsheet E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.dispatch.tripsheet, PID: 20228
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dispatch.tripsheet/com.dispatch.tripsheet.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3835)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8633)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.dispatch.tripsheet.MainActivity.onCreate(MainActivity.kt:25)
        at android.app.Activity.performCreate(Activity.java:8207)
        at android.app.Activity.performCreate(Activity.java:8191)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3808)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:246) 
        at android.app.ActivityThread.main(ActivityThread.java:8633) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) 

我不确定这到底是什么意思。只是告诉我按钮会发生一些事情。但我不知道更多。 Image to show the app before crash. So everything works until I try to add a clicklistener.

您的按钮似乎没有找到。您如何访问它以及在哪里访问它?请记住,按钮首先需要存在,以便您可以获得对它的引用。您可以使用 findViewById 方法或视图绑定。

@helpVulcan 这是您可以根据需要使用和自定义的适配器代码片段,

class MyAdapter(val list: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.table_list_item, parent, false))
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.apply {
            button1.setOnClickListener {
                Log.e("Clicked", "button1")
                //  Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    class MyViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        var button1 = view.findViewById<Button>(R.id.button1)
    }

}

借助此 post 和更多研究,我找到了解决方案。 我知道我的问题是按钮的 creating/calling。我的按钮不在我的主 activity xml 文件中,而是在另一个文件中。所以在我的适配器中是我必须放置代码的地方。

package com.dispatch.tripsheet



import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.table_list_item.view.*

class TableViewAdapter(private val movieList: List<MovieModel>) : RecyclerView.Adapter<TableViewAdapter.RowViewHolder>() {



  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RowViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.table_list_item, parent, false)
        return RowViewHolder(itemView)


    }

    private fun setHeaderBg(view: View) {
        view.setBackgroundResource(R.drawable.table_header_cell_bg)
    }

    private fun setContentBg(view: View) {
        view.setBackgroundResource(R.drawable.table_content_cell_bg)
    }

    override fun onBindViewHolder(holder: RowViewHolder, position: Int) {
        val rowPos = holder.adapterPosition



        if (rowPos == 0) {
            // Header Cells. Main Headings appear here
            holder.itemView.apply {
                setHeaderBg(txtWOrder)
                setHeaderBg(txtDElNote)
                setHeaderBg(txtCompany)
              //  setHeaderBg(txtAddress)
                setHeaderBg(txtWeight)
                setHeaderBg(txtbutton1)
                setHeaderBg(txtbutton2)
                setHeaderBg(txttvdone)


                txtWOrder.text = "WOrder"
                txtDElNote.text = "DElNote"
                txtCompany.text = "Company"
               // txtAddress.text = "Address"
                txtWeight.text = "Weight"
                txtbutton1.text = "Delivered"
                txtbutton2.text = "Exception"
                txttvdone.text = ""
            }
        } else {
            val modal = movieList[rowPos - 1]

            holder.itemView.apply {
                setContentBg(txtWOrder)
                setContentBg(txtDElNote)
                setContentBg(txtCompany)
              //  setContentBg(txtAddress)
                setContentBg(txtWeight)
                setContentBg(txtbutton1)
                setContentBg(txtbutton2)
                setContentBg(txttvdone)

                txtWOrder.text = modal.WOrder.toString()
                txtDElNote.text = modal.DElNote.toString()
                txtCompany.text = modal.Company.toString()
              //  txtAddress.text = modal.Address.toString()
                txtWeight.text = modal.Weight.toString()
                txtbutton1.text = modal.Button1.toString()
                txtbutton2.text = modal.Button2.toString()
                txttvdone.text = modal.tvdone.toString()
            }
        }

        holder.apply {
            txtbutton1.setOnClickListener {
                Log.e("Clicked", "Successful delivery")
                txttvdone.setBackgroundResource(R.color.green)
            }
            txtbutton2.setOnClickListener {
                Log.e("Clicked", "Exception on delivery")
                txttvdone.setBackgroundResource(R.color.orange)
            }
        }

    }

    override fun getItemCount(): Int { return movieList.size + 1 // one more to add header row
        }

     class RowViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){


         val txttvdone:TextView = itemView.findViewById<TextView>(R.id.txttvdone)
         val txtbutton1:Button = itemView.findViewById<Button>(R.id.txtbutton1)
         val txtbutton2:Button = itemView.findViewById<Button>(R.id.txtbutton2)
     }

    class MyViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        var txtbutton1 = view.findViewById<Button>(R.id.txtbutton1)
        val txtbutton2:Button = itemView.findViewById<Button>(R.id.txtbutton2)
        var txttvdone = view.findViewById<TextView>(R.id.txttvdone)
    }
}