how to access a variable after modifying it

Issue

I have tried to simplify my problem as much as possible, I hope it is clear what I am asking.

I would like to obtain in the fragment the value of the variable pto1 after modifying it through the onClickEvent function of class B.
I understood that doing so is not possible because when I have

val classA = A ()

in the fragment,a new instance of class A is recreated and a new pto1 it is recreated and set to 0.0 .

how can i access pto1 from fragment after modifying it with class B?

class A {
    var pto1 = 0.0
    
    fun changeValue(a: Double){
        pto1 = a
    }
}
--------------------------------
class B {

    val classA = A()

    fun onClickEvent(b:Double){
        classA.changeValue(b)
    }

}
--------------------------------
fragment D {
    val classA = A()
    onCreateView( ... ){
        val botton = view.findViewById<Button>(R.id.button)
        button.setOnClickListner{
            val f = classA.pto1
        }
    }
}

Solution

There is a couple of options here

Make it static

class A {
    companion object {
       var pto1 = 0.0
    }
}

Is this a View Model problem?

Use the navgraph viewmodel or a viewmodel from the activity.

Make it persistent: you can use the SharedPreferences or ROOM to save it.

Make the host of both fragments have it and then fragments can acces it. If the host is the activity:

class MyActivity {

    val a = A()
    
     fun getA() = a

}
(requireActivity() as? MyActivity).?getA()

Is this a navigation result?
Take a look here How to get a result from fragment using Navigation Architecture Component?

Answered By – cutiko

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published