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?
2
Answers
"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.
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 fromonCreateView()
while inflating the layout.So in short the correct way to get text from an EditText is this:
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.