Caused by: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.EditTextat com.example.login.MainActivity.onCreate(MainActivity.kt:18) at android.app.Activity.performCreate(Activity.java:7009) at android.app.Activity.performCreate(Activity.java:7000) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is my kotlin code where error is coming:
val Name = findViewById<EditText>(R.id.etName)
val Password = findViewById<EditText>(R.id.etpassword)
val Login = findViewById<Button>(R.id.btnlogin)
val Info = findViewById<TextView>(R.id.tvinfo)
?xml version="1.0" encoding="utf-8"?>
<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/etName"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
Looks like you have
android:id="@+id/etName"
in your root ConstraintLayout
. In code you have
val Name = findViewById<EditText>(R.id.etName)
which finds a view by id etName
and attempts to cast it to EditText
. The algorithm in findViewById()
is just a simple tree search that stops at first match which is the root layout for you. If you have another view (such as your EditText
) with the same id, the search never reaches that deep. Bang, ClassCastException
.
To fix it, remove the id from the root layout, or change it to something unique within the layout file, and ensure you actually have an EditText
with id etName
in the layout.