1

I am updating a view in activity's onCreate method which is working fine using kotlin extension as stated below.

Activity's onCreate

import kotlinx.android.synthetic.main.activity_otpverification.*

     override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_otpverification)
            tvContactNumber.text = getString(R.string.dual_string_value_placeholder)
        }

Then at a click of a button I am showing a custom dialog for performing some action. When the dialog is dismissed I update the same textView in activity with the data sent from dialog, but the view tvContact is throwing null exception.

Activity's onClick

override fun onClick(p0: View?) {
    when (p0?.id) {
        R.id.ivEdit -> {
            object : ChangeNumberDialog(this) {
                override fun onSubmitClicked(number: String) {
                    tvContactNumber.text =number
                }
            }.show()
        }
    }
}

onSubmitClicked is an abstract method in the dialog which is triggered when the dialog is dismissed.

Error from logcat :

    java.lang.IllegalStateException: tvContactNumber must not be null
            at com.beat.em.ui.activities.OTPVerificationActivity$onClick$1.onSubmitClicked
(OTPVerificationActivity.kt:211)

onCreate and onClick methods from the ChangeNumberDialog:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = layoutInflater.inflate(R.layout.dialog_change_number, null, false)
        setContentView(view)
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        tvSubmit.setOnClickListener(this)
    }

  override fun onClick(view: View) {
    when (view.id) {
        R.id.tvSubmit -> {
            onSubmitClicked(etNumber.text.toString().trim())
            dismiss()
          }
       }
  }

I have just started using kotlin extension and not able to understand the cause. Help appreciated.

Bee
  • 142
  • 17

1 Answers1

2

The variable you are trying to access is in another scope, try to add explicit scope to the view i.e.

this@YourActivity.tvContactNumber.text = number
Darshan
  • 4,020
  • 2
  • 18
  • 49
Wackaloon
  • 2,285
  • 1
  • 16
  • 33