Parcelable executes twice the init block on android with kotlin

1

I have a custom class that I am sending from an activity to a tabbed activity (fragments) using parcelable .

In the init block of my custom class I execute a function to transform one of the values that arrive to the constructor when I create my class, but parcelable when constructing the object again, it goes through the init block executing its functions of new and damaging my transformation of values. Why is this happening?

Sending the data of an activity

    val intent = Intent(ctx, resultado_calculadora_requerimientos::class.java)
    val bundle = Bundle()
    bundle.putParcelable("requerimientos", requerimientos)
    intent.putExtra("bundle", bundle)
    startActivity(intent)

Passing the data to the fragment

override fun getItem(position: Int): Fragment {
        var fragment : Fragment? = null
        val bundle :Bundle = intent.getBundleExtra("bundle")
        when(position){
            0 -> fragment = resultado_calculadora_requerimientos_frag1()
            1 -> fragment = resultado_calculadora_requerimientos_frag2()
        }
        fragment!!.arguments = bundle
        return fragment!!
    }

** And when they arrive at the fragment **

if (arguments != null) {
        requerimientos = arguments!!.getParcelable<Parcelable>("requerimientos") as Requerimientos?
    }

The declaration of my class

class Requerimientos (
    // CONSTRUCTOR
    var peso: Double                     ,
    private var altura: Double           ,
    private val edad: Int                ,
    private val actividad_fisica: String ,
    private val sexo: String             ,
    val unidad_medida :Int        /* 0 - cm y kg / 1 - lb y in */) : Parcelable {
constructor(parcel: Parcel) : this(
        parcel.readDouble(),
        parcel.readDouble(),
        parcel.readInt(),
        parcel.readString(),
        parcel.readString(),
        parcel.readInt()) {
    factorAgua  = parcel.readDouble()
    factorProt  = parcel.readDouble()
    factorLip   = parcel.readDouble()
    factorCh    = parcel.readDouble()
}

init{
    if (unidad_medida == 1){
        this.peso   = this.lbAkg(this.peso)
        this.altura = this.inAcm(altura)
        Log.d("waskjas", "Cambiando los valores de peso y altura a cm y kg")
        Log.d("waskjas", "valor peso: $peso")
        Log.d("waskjas", "valor altura: $altura")
    }
}
    
asked by César Alejandro M 16.10.2018 в 02:39
source

0 answers