вылетает при открытии приложения

приложение справочник растений вылетает как только я его открываю, использую RecyclerView

MainActivity:

class MainActivity : AppCompatActivity() {
    private lateinit var bindingClass: ActivityMainBinding
    private val adapter = PlantAdapter()
    private var launcher: ActivityResultLauncher<Intent>? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        bindingClass = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bindingClass.root)
        init()

        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            if(it.resultCode == RESULT_OK){
                adapter.addPlant(it.data?.getSerializableExtra("plant") as Plant)
            }
        }
    }

    private fun init() {
        bindingClass.apply {
            rcView.layoutManager = GridLayoutManager(this@MainActivity, 3)
            rcView.adapter = adapter
            buttonAdd.setOnClickListener {
                launcher?.launch(Intent(this@MainActivity, EditActivity::class.java))
            }
        }
    }
} 

EditActivity:

class EditActivity : AppCompatActivity() {
    lateinit var bindingClass: ActivityEditBinding
    private var indexImage = 0
    private var imageIdLIst = listOf(R.drawable.aloe_traski,
        R.drawable.amarillis,
        R.drawable.alststromeria,
        R.drawable.agapantus,
        R.drawable.allium)
    private var imageId = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        bindingClass = ActivityEditBinding.inflate(layoutInflater)
        setContentView(bindingClass.root)
    }

    fun initButtons(view: View) = with(bindingClass){
        bSkipImage.setOnClickListener{
            indexImage++
            if(indexImage > imageIdLIst.size - 1) indexImage = 0
            Log.d("MyLog", "Index = $indexImage")
        }
    }
    
    
}

Plant:

data class Plant(val imageId: Int, val title: String, val description: String): Serializable

PlantAdapter:

class PlantAdapter : RecyclerView.Adapter<PlantAdapter.PlantHolder>() {
    val plantList = ArrayList<Plant>()

    class PlantHolder(item: View): RecyclerView.ViewHolder(item) {
        val binding = PlantItemBinding.bind(item)
        fun bind(plant: Plant){
            binding.im.setImageResource(plant.imageId)
            binding.tvTitle.text = plant.title
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlantHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.plant_item, parent, false)
        return PlantHolder(view)
    }

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

    override fun onBindViewHolder(holder: PlantHolder, position: Int) {
        holder.bind(plantList[position])
    }

    fun addPlant(plant: Plant){
        plantList.add(plant)
        notifyDataSetChanged()
    }
}

activity_edit:

<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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#A8A4A4"
    tools:context=".EditActivity">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="270dp"
                android:layout_height="210dp"
                android:layout_margin="5dp"
                tools:srcCompat="@drawable/allium" />
        </LinearLayout>

        <Button
            android:id="@+id/bSkipImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:onClick="initButtons"
            android:text="Next Image"
            android:visibility="visible" />

    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/cardView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/cardView"
        app:layout_constraintVertical_bias="1.0">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <EditText
                android:id="@+id/edTitle"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:ems="10"
                android:hint="Title"
                android:inputType="text"
                tools:ignore="TouchTargetSizeCheck" />

            <EditText
                android:id="@+id/edDescription"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:ems="10"
                android:hint="Description"
                android:inputType="text"
                tools:ignore="TouchTargetSizeCheck" />

            <Button
                android:id="@+id/bDone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Done" />
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_main:

<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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C3BFBF"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcView"
        android:layout_width="409dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00999999" />

    <Button
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="110dp"
        android:text="Add Plant"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

plant_item:

<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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:cardCornerRadius="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/im"
                android:layout_width="wrap_content"
                android:layout_height="125dp"
                android:layout_margin="3dp"
                android:src="@drawable/allium" />

            <TextView
                android:id="@+id/tvTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:fontFamily="sans-serif-condensed"
                android:gravity="center"
                android:text="TextView"
                android:textColor="#000000"
                android:textSize="16sp"
                android:textStyle="bold" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.RecyclerView"
        tools:targetApi="31">

        <activity
            android:name=".EditActivity"
            android:exported="false" />

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Лог из LogCat:

FATAL EXCEPTION: main (Ask Gemini)
                                                                                                    Process: com.example.recyclerview, PID: 20926
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.recyclerview/com.example.recyclerview.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnApplyWindowInsetsListener(android.view.View$OnApplyWindowInsetsListener)' on a null object reference
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4164)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4322)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2685)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230)
                                                                                                        at android.os.Looper.loop(Looper.java:319)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8893)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnApplyWindowInsetsListener(android.view.View$OnApplyWindowInsetsListener)' on a null object reference
                                                                                                        at androidx.core.view.ViewCompat$Api21Impl.setOnApplyWindowInsetsListener(ViewCompat.java:5284)
                                                                                                        at androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(ViewCompat.java:2962)
                                                                                                        at com.example.recyclerview.MainActivity.onCreate(MainActivity.kt:23)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8944)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8913)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1456)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4146)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4322) 
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139) 
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96) 
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2685) 
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230) 
                                                                                                        at android.os.Looper.loop(Looper.java:319) 
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8893) 
                                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608) 
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103) 
2024-12-28 21:42:15.951   892-1236  BufferQueueDebug        surfaceflinger                       E  [Surface(name=1667e5b NavigationBar0)/@0x55ad5d1 - animation-leash of insets_animation#409](this:0xe75e90b8,id:-1,api:0,p:-1,c:-1) id info cannot be read from 'Surface(name=1667e5b NavigationBar0)/@0x55ad5d1 - animation-leash of insets_animation#409'

Я знаю что в приложении много hard кода и то что оно еще не готово даже данные не сохраняются но я не понимаю почему у меня вылетает сейчас мне нужно посмотреть на сам edit_activity чтоб понимать от чего отталкиваться но я не совсем понимаю в чем проблема


Ответы (1 шт):

Автор решения: Eugene Krivenja

Нельзя вызывать

ViewCompat.setOnApplyWindowInsetsListener(findViewById(...))

до того как вызван

setContentView(...)

Потому что findViewById(...) вернет null

→ Ссылка