Ad

Kotlin LateInit Has Not Been Initialised Error Crashing Application

I have an Android Kotlin application fragment with three elements in the resource layout:

<EditText android:id="@+id/forename_input_account"/>
<EditText android:id="@+id/surname_input_account"/>
<Button android:id="@+id/saveButton"/>

On clicking save I require the contents of the two EditText fields to write to the project Firebase Realtime DB.

In the account fragment file, I have the following:

class AccountFragment : Fragment() {

    lateinit var forename_input_account: EditText
    lateinit var surname_input_account: EditText
    lateinit var saveButton: Button

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

            forename_input_account = forename_input_account
            surname_input_account = surname_input_account
            saveButton = saveButton

            saveButton.setOnClickListener {
                saveAccount()
            }

    }

    private fun saveAccount(){
        val firstname = forename_input_account.text.toString().trim()
        val lastname = lastname_input_account.text.toString().trim()

        val ref = FirebaseDatabase.getInstance().getReference("mySaveLocation")
        val saveId = ref.push().key

        val myRecord = save(saveId, firstname, lastname)

        ref.child(saveId.toString()).setValue(myRecord).addOnCompleteListener{

        }
    }

}

firstname and lastname are being declared in a separate file as follows:

class Hero(val id: String?, val firstname: String, val lastname: String)

When I run the application and navigate to the fragment the application crashes with the following error:

kotlin.UninitializedPropertyAccessException: lateinit property forename_input_account has not been initialized

Ad

Answer

forename_input_account = forename_input_account sets forename_input_account to itself. That has no practical effect, and since you are trying to access the lateinit var before you assign a value to it, you crash.

If you are trying to use Kotlin synthetic properties, remove the three lateinit var properties and just use Kotlin synthetic properties, scoped to refer to the inflated view.

Otherwise, you need to use findViewById() or something to get the View to assign to those lateinit var properties (e.g., forename_input_account = view.findViewById(R.id.forename_input_account)).

Ad
source: stackoverflow.com
Ad