Home > Software design >  button.setOnClickListener is crashing my app. Kotlin 1.3.72
button.setOnClickListener is crashing my app. Kotlin 1.3.72

Time:03-11

So firstly I know that kotlin android extensions are not supported anymore. I will change that later. First I want to make sure my app works and has what it needs then Ill converge over. I am somewhat new to android studio so there is a chance I missed something simple. I did Import button and toast.

My app works fine if I remove the button onclick listener so I assume it must be the culprit.

Main 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")



    }


}



Full 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>


This one is to fill my recyclerview. The one to follow is my 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>

I have removed the toast and the color change to see if that might be it. But it still crashed. So not sure what I am missing.

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) 

I am not sure what it means exactly. Just shows me it happens something with the button. But I do not know much more. Image to show the app before crash. So everything works until I try to add a clicklistener.

CodePudding user response:

@helpVulcan Here is the adapter code snippet which you can use and customise as per your requirement,

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)
    }

}

CodePudding user response:

It looks like your button was not found. How are you getting access to it and where? Remember that the button needs to exist first so you can get the reference to it. You can use either the findViewById method or view binding.

  • Related