-1

When I use apply,"kotlin-android-extensions" find id is null

   private val nickDialog: NickDialog by lazy {
        NickDialog(this@AccountInformationActivity).apply {
            this.setOnClickConfirmListener {
                account_nick.setRightText(it)
                this.dismiss()
            }
        }
    }

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.cnjnb.wealthstorm.view.TextLineView.setRightText(java.lang.String)' on a null object reference.

But when I use this, it's OK.

    private val nickDialog: NickDialog by lazy {
        val a = NickDialog(this@AccountInformationActivity)
        a.setOnClickConfirmListener {
            account_nick.setRightText(it)
            a.dismiss()
        }
        a
    }

XML: account_nick is view'id in my XML

Part of it is :

  <com.cnjnb.wealthstorm.view.TextLineView
        android:id="@+id/account_nick"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintTop_toBottomOf="@id/account_profession"
        app:leftText="nick"
        app:rightText="bright" />
ardiien
  • 767
  • 6
  • 26
Symphony
  • 13
  • 3

1 Answers1

0

It seems that the source of your problem is account_nick property. When you call it insinde dialogs apply, code executes for it - he tries to find that view inside the dialog. While it's activities view, here you got null.

To avoid it you can place this@YourActivityClass before account_nick call.

private val nickDialog: NickDialog by lazy {
    NickDialog(this@AccountInformationActivity).apply {
        this.setOnClickConfirmListener {
            this@AccountInformationActivity.account_nick.setRightText(it)
            this.dismiss()
        }
    }
}
Ircover
  • 2,406
  • 2
  • 22
  • 42