Kotlin Data Class, Android Room and Custom Setter

I have an Android Room object that looks like this. Don't worry just yet.

@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                @ColumnInfo(name = "password") var password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
}

      

Now I need to encrypt the password. With Java, this will just be done with the installer and it will work.

How would you do it with Kotlin. I can't seem to find a solution to combine Android Room, custom settings and data classes.

+3


source to share


2 answers


You can try something like this:

@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                private var _password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0

    @ColumnInfo(name = "password")
    var password: String = _password
        set(value) {
            field = "encrypted"
        }

    override fun toString(): String {
        return "User(id=$id, nickName='$nickName', password='$password')"
    }

}

      



But I would not recommend encrypting the password inside the Entity or modifying it in any way, since it is not its responsibility and you may run into errors with double encrypting your password, like when fetching your object from the database. The room will fill the object with data, which will encrypt the already encrypted data.

+2


source


    @Entity(tableName = "users",
            indices = arrayOf(Index(value = "nickName", unique = true)))
    data class User(@ColumnInfo(name = "nickName") var nickName: String,
                    @ColumnInfo(name = "password") var password: String) {
    var _password = password
        set(value): String{
           //encrypt password
        }
        @ColumnInfo(name = "id")
        @PrimaryKey(autoGenerate = true)
        var id: Long = 0
    }

      



This will create a custom setter, so every time you set your password, you can encrypt it inside the installer too.

-4


source







All Articles