Search code examples
androidkotlinpojo

Unable to update pojo class in Kotlin


I am trying to update my pojo class on a particular click in Kotlin but it is giving me error :-

java.lang.stackoverflowerror: stack size 8mb

Here is my Pojo Class

class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean){
    var title1: String = title
        //  get() = title                    // Calls the getter recursively
        set(value)
        { title1 = value }

    var image: Int = icon_normal
        // get() = image
        set(value)
        { image = value }

    var image_notified: Int = icon_notified
        // get() = image
        set(value)
        { image_notified = value }


    var notify: Boolean = isShowNotify
        set(value) {
            notify = value
        }
}

I am updating my Pojo on the Item click of NavigationDrawer

override fun onItemClick(position: Int) {
        mDrawerLayout?.closeDrawer(this!!.containerView!!)
        position1 = position
        for (i in navDrawerItems.indices) {
            val item = navDrawerItems[i]
            item.notify=(if (i == position) true else false)
            navDrawerItems[i] = item
            mAdapter?.notifyDataSetChanged()
        }
    }

Please help me!!!!


Solution

  • Your setters create infinite loop, which causes the StackOverflowError exceptions.

    class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean){
        var title1: String = title
            //  get() = title                    // Calls the getter recursively
            set(value)
            { field = value }
    
        var image: Int = icon_normal
            // get() = image
            set(value)
            { field = value }
    
        var image_notified: Int = icon_notified
            // get() = image
            set(value)
            { field = value }
    
    
        var notify: Boolean = isShowNotify
            set(value) {
                field = value
            }
    }
    

    The above is setting the field, where your implementation was recursively setting the values.

    Also, as ADM mentioned it's better to move the notifyDataSetChanged outside of the loop and not updating at each iteration.