简体   繁体   English

lateinit property has not been initialized 错误发生

[英]lateinit property has not been initialized error occur

I am studying with Kotlin and I have not been able to solve the error for several days, so I am asking for help.我正在用Kotlin学习,好几天没能解决错误,求助。
I am trying to retrieve data from the room database and put it into a variable(productlist), but an error occurs as follows.我试图从房间数据库中检索数据并将其放入变量(productlist)中,但出现如下错误。

kotlin.UninitializedPropertyAccessException: lateinit property productList has not been initialized kotlin.UninitializedPropertyAccessException: lateinit 属性 productList 尚未初始化

Here is my source codes.这是我的源代码。 I already checked that the room database contains data normally.我已经检查过房间数据库是否正常包含数据。
I want to put data fetched from db in productList variable and use it.我想把从 db 中获取的数据放在 productList 变量中并使用它。
Thanks in advance!提前致谢!

[MainActivity.kt] [主要活动.kt]

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var PACKAGE_NAME: String
    private var currentPosition: Int = 0
    private var lastPosition: Int = 0
    private lateinit var db: AppDatabase
    private lateinit var productDao: ProductDao
    private lateinit var productList: List<ProductEntity>
    private var urls: String = ""
    private var titles: String = ""
    private var descs: String = ""
    private var isVideos: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
     
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        db = AppDatabase.getInstance(this)!!
        productDao = db.getProductDao()
        setVideoItem()
    }

    private fun setVideoItem() {
        val videosViewPager = binding.viewPagerVideos
        val videoItems: MutableList<VideoItem> = ArrayList()
        val files = File(this@MainActivity.filesDir, "products").listFiles()
        Thread {
            productList = productDao.getAll()
        }.start()
        for (i in productList) { //I want to store accessed data to productList variable 
            urls += "${i.idx}:"
            titles += "${i.name}:"
            descs += "${i.price}:"
        }
        println("urls:$urls")
        println("titles:$titles")
        println("descs:$descs")

    }

[ProductDao.kt] [ProductDao.kt]

@Dao
interface ProductDao {
    @Query("select * from ProductEntity")
    fun getAll() : List<ProductEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(product: ProductEntity)

    @Query("select idx, name, price from ProductEntity where idx like :searchIdx")
    fun searchProductByIdx(searchIdx: String) : ProductEntity

}

productDao.getAll() is called on a separate thread which takes time to execute. productDao.getAll()在一个单独的线程上调用,这需要时间来执行。 So you're trying to access productList before the thread initializes it.所以你试图在线程初始化它之前访问productList

It's race condition in which the thread always loses.这是线程总是失败的竞争条件。

Relocating the code that uses productList to the thread should solve this race:将使用productList的代码重新定位到线程应该可以解决这个竞争:

Thread {
    productList = productDao.getAll()
    for (i in productList) { 
        urls += "${i.idx}:"
        titles += "${i.name}:"
        descs += "${i.price}:"
    }
    println("urls:$urls")
    println("titles:$titles")
    println("descs:$descs")
}.start()
Thread {
            productList = productDao.getAll()
        }.start()

Product list is being fetched in a thread in a parallel process so since it is not synchronous when the control is on the line for (i in productList) according to the program the product list has not been initialized.. You have to decide how you handle this concurrency.产品列表是在并行进程中的线程中获取的,因此根据程序,当控件在线时它不是同步的for (i in productList) ,产品列表尚未初始化。您必须决定如何处理这个并发。 either call the method synchronously or populate the list after iteration via some method or do it in the same thread.要么同步调用方法,要么在迭代后通过某种方法填充列表,或者在同一个线程中执行。

Something like就像是

Thread {
    productList = productDao.getAll()
    //iterate through the list 
    //print the values
}.start()

Start a thread to access db,it will take some time.The main thread will not wait for the thread accessing the database to complete, so it is uninitialized to read productList at this time.启动一个线程访问db,需要一定的时间,主线程不会等待访问数据库的线程完成,所以此时未初始化读取productList。

You can access the list after loading is complete, or use Android Handler to notify the main thread of the update after loading is complete.加载完成后可以访问列表,或者加载完成后使用Android Handler通知主线程更新。

Thread {
        productList = productDao.getAll()
        for (i in productList) {
            urls += "${i.idx}:"
            titles += "${i.name}:"
            descs += "${i.price}:"
        }
        println("urls:$urls")
        println("titles:$titles")
        println("descs:$descs")
}.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:lateinit 属性 recyclerViewAdapter 尚未初始化 - Error: lateinit property recyclerViewAdapter has not been initialized lateinit 属性 NotaViewModel 尚未初始化错误 - lateinit property NotaViewModel has not been initialized Error lateinit 属性尚未初始化 - lateinit property has not been initialized 在 onCreateView 中初始化的变量出现“Lateinit 属性尚未初始化”错误 - “Lateinit property has not been initialized” error on a variable initialized in onCreateView Hilt 和 WorkManager 错误:lateinit 属性 WorkerFactory 尚未初始化 - Hilt and WorkManager error : lateinit property WorkerFactory has not been initialized 我无法解决这个错误“lateinit property dataBinding has not been initialized” - I cant solve this error "lateinit property dataBinding has not been initialized" 如何在 kotlin 中初始化 lateinit 属性。 错误“kotlin.UninitializedPropertyAccessException:lateinit 属性学生尚未初始化” - How to initialize lateinit property in kotlin. error "kotlin.UninitializedPropertyAccessException: lateinit property student has not been initialized" lateinit 属性 ABC 尚未初始化 - lateinit property ABC has not been initialized lateinit 属性 llMain(RecyclerView) 尚未初始化 - lateinit property llMain(RecyclerView) has not been initialized lateinit 属性 providerFactory 尚未初始化 - lateinit property providerFactory has not been initialized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM