无法在Kotlin中更新pojo类

问题描述 投票:0回答:3

我想在Kotlin的特定点击中更新我的pojo课程,但它给了我错误: -

java.lang.stackoverflowerror:堆栈大小为8mb

这是我的Pojo课程

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
        }
}

我正在点击导航抽屉的项目更新我的Pojo

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()
        }
    }

请帮我!!!!

android kotlin pojo
3个回答
1
投票

你的setter创建无限循环,这会导致StackOverflowError异常。

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
        }
}

以上是设置字段,您的实现以递归方式设置值。

此外,正如ADM所提到的,最好将notifyDataSetChanged移到循环之外,而不是在每次迭代时更新。


1
投票

将您的类修改为简单的data class

data class NavDrawerItem(var icon_normal: Int,var icon_notified: Int, var title: String, var isShowNotify: Boolean)

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

0
投票

始终建议使用数据类来定义pojos。因为数据类仅用于存储数据。 它们在kotlin中提供了许多与普通类相比的独特功能。 例如,您不需要定义setter和getter,它们会自动添加到您的数据类中。 此外,您的数据类将自动覆盖一些有用的函数,如equals,hashCode,toString等。

定义数据类非常容易。

data class Foo ( val title : String, val isHungry : Boolean ){

}
© www.soinside.com 2019 - 2024. All rights reserved.