skip to Main Content

Android studio Bumblebee 2021.1.1

All I am simply trying to do is get or retrieve text input from edittext field and it simply doesn’t work no matter how I do it. I have searched everywhere including stackoverflow for solution or answer but with no success. Here is my code.

...
val courseNameEdt = findViewById<EditText>(R.id.idEdtCourseName)
...
addCourseBtn.setOnClickListener{
        
        var courseName = courseNameEdt.text.gettext() //doesn't work | unresolved reference gettext() and won't compile
        //var courseName = courseNameEdt.text           doesn't work either | app compiles, crashes and stops running when launched
        //var courseName = courseNameEdt.text.toString()doesn't work either | app compiles, crashes and stops running when launched
}

So, what am I doing wrong? Is there a fourth ways to do this?

enter image description here

2

Answers


  1. "courseNameEdt.text" is the answer. The reason that it crashes is because the view with id "idEdtCourseName" is either inaccessible on that screen or is not an EditText. Use ViewBinding.

    Login or Signup to reply.
  2. The First method var courseName = courseNameEdt.text.gettext() won’t work obviously.

    The second and third ones are correct syntactically but the crashed might be for different reasons, which would be helpful if you could share.

    Now there can be any problem like improper id, or if you are you using in onViewCreated() of fragment then you need an instance of the view from onCreateView() while inflating the layout.

    So in short the correct way to get text from an EditText is this:

     var courseName = courseNameEdt.text.toString()
    

    there is another way to get and set text with binding, but i guess you are a beginner and hence wouldn’t have any idea about that.

    So, the crashes might be due to different reasons but the correct way to fetch text is the ways mentioned above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search