Reputation: 49
I am new to Firebase. I have made a simple project which sends user strings to Realtime Database in Firebase. For input, I have used the EditText view. Here is my main activity. username is the id of EditText View
package com.example.firebase
import...
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var database: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.Remote.setOnClickListener {
val name = binding.username.text.toString() //Error on this line
database = FirebaseDatabase.getInstance().getReference("Users")
val User = User(name)
database.child(name).setValue(User).addOnSuccessListener {
binding.username.text.clear() //And This Line
Toast.makeText(this,"Sucess", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this,"Failed", Toast.LENGTH_SHORT).show()
}
}
After Building following error is shown on the commented line of code:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type EditText.
It works fine if I direct enter a string instead of using EditText View. Can someone help me with this?
Upvotes: 1
Views: 41
Reputation: 139019
It looks like your username
EditText object is null. So there are two ways in which you solve this problem:
Use safe call (?.)
val name = binding.username?.text.toString()
// 👆
Use a non-null asserted (!!.)
val name = binding.username!!.text.toString()
// 👆
See more info inside the Kotlin documentation regarding null safety.
Upvotes: 2
Reputation: 19592
Do you have different versions of that layout file (e.g. portrait/landscape, small screen, different API level etc)? Check you have an EditText
with an ID of username
in all of them - if it's missing from some variations, the generated binding class makes that property nullable, since it might not be present (depending on which version of the layout file was inflated)
Upvotes: 0