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?
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.