skip to Main Content

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?

2

Answers


  1. The EditText#gettext() function returns an object of type Editable!. This type of object can be null, see the ! (exclamation mark)? So there are two ways in which you solve this problem:

    1. Use safe call (?.)

       val name = binding.username.text?.toString()
       //                             👆
      
    2. Use a non-null asserted (!!.)

       val name = binding.username.text!!.toString()
       //                              👆
      

    See more info inside the Kotlin documentation regarding null safety.

    Login or Signup to reply.
  2. 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)

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