简体   繁体   中英

Kotlin / lateinit property binding has not been initialized

I working on Quiz App from YT tutorial and I am facing the issue with lateinit property binding has not been initialized .

Here its the part where i have initialized binding, i get error in bolded words: binding = MessageItemBinding .inflate( inflater )

Code part

class QuizQuestionActivity : AppCompatActivity(), View.OnClickListener {

private lateinit var binding: ActivityQuizQuestionBinding
private var mCurrentPosition: Int = 1 // Default and the first question position
private var mQuestionsList: ArrayList<Question>? = null
private var mSelectedOptionPosition: Int = 0
private var mCorrectAnswers: Int = 0

private var mUserName: String? = null

override fun onCreate(savedInstanceState: Bundle?) {
    binding = DataBindingUtil.inflate(inflater, R.layout.message_item, container, false)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_quiz_question)

    mUserName = intent.getStringExtra(Constants.USER_NAME)

    mQuestionsList = Constants.getQuestions()

    setQuestion()

    binding.tvOptionOne.setOnClickListener(this)
    ...
}

Here's my graddle. Maybe you would what's missing

plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
...

buildFeatures {
    viewBinding true
}

kapt {
    generateStubs = true
}

...

dependencies {

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.google.android.material:material:1.1.0-alpha10'
kapt 'com.android.databinding:compiler:2.0.0-rc1'

}

You are not properly setting up the binding I assume. The following code seems the issue

  binding = DataBindingUtil.inflate(inflater, R.layout.message_item, container, false)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_quiz_question)

Instead you can simply let it be like this. You are currently setting up binding of some other layout to your activity.

super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_quiz_question)

Refer here for more: https://developer.android.com/topic/libraries/data-binding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM