Issue
when i try to initialize data class it gives me error, kotlin.UninitializedPropertyAccessException: lateinit property article_ has not been initialized. How do i resolve this error and whats way to initialize data class.
model class
data class Article(
val id: Int,
val author: String,
val content: String,
val description: String?)
MainActivity
class TestActivity : AppCompatActivity() {
lateinit var binding: ActivityTestBinding
lateinit var article_: List<Article>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_test)
val mainAdapter = MainAdapter(article_)
binding.recView.apply {
this.layoutManager = LinearLayoutManager(this@TestActivity)
this.adapter = mainAdapter
}
}
}
Solution
ANSWER:
In onCreate()
before this line val mainAdapter = MainAdapter(article_)
just initialize the article_
by writing article_ = ArrayList()
and the error will be gone.
Cause of Error
You are encountering this error because You need to initialize the lateinit variable article_
before using it and you are not doing it.
If you want to check that either the variable is initialized or not then use ::article_.isInitialized
.
Feel free to ask if something is unclear.
Answered By - Kamal Nayan
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)