2

I want get "id" from data class cartDocs in this Activity. I am trying to run this code, but got error like this: kotlin.UninitializedPropertyAccessException: lateinit property cart has not been initialized I also tried to remove "?" in data class. but still same problem. How can I solve this problem?

class CartViewActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {




    lateinit var cart: cartDocs

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cart_view)

        val token = SharedPreference.getTokenInfo(this)

        Client.retrofitService.getCart(token).enqueue(object :Callback<CartResponse> {
            override fun onResponse(call: Call<CartResponse>, response: Response<CartResponse>) {
                swipeRefreshLo.setOnRefreshListener(this@CartViewActivity)
                showdata(response.body()?.docs!!)
                val itemId = cart.id
                if (itemId!=null){
                    SharedPreference.setCartId(applicationContext,itemId)
                }
            }

            override fun onFailure(call: Call<CartResponse>, t: Throwable) {

            }


        })

data class cartDocs

data class cartDocs(

    var id:String?=null,

    var title:String?=null,

    var stock:Int?=null,

    var availableAfter:String?=null,

    var price:Int?=null,

    var point:Int?=null,

    var mainImage:String?=null,

    var description:MutableList<cartDescription>,

    var amount:Int?=null,

    var added:String?=null,

    var options:MutableList<cartOptions>,

    var unitPrice:Int?=null,

    var unitPoint:Int?=null,

    var totalPrice:Int?=null,

    var totalPoint:Int?=null
)



1 Answers1

1

lateinit was designed for cases when you need to init a variable some time after object creation - for example frameworks like dagger. In fact it allows to use lateinit variable as normal not null value (and get rid of unnecessary ?/!! operators) but the programmer is responsible to make sure that value is initialized before the use.

In your case you try to use that variable before it's initialized. So, you get given exception. What you need is to initialize that value at some point. But, I would think about the design - seems that what you need is a nullable type and using lateinit here is not reasonable. It will enforce on you checking if value is not null before any use of that value.

If you are interested in lateinit design in JVM you can see my old answer to other question: How to uninitialize lateinit in Kotlin

Cililing
  • 4,303
  • 1
  • 17
  • 35