Keshav Khetan
Keshav Khetan

Reputation: 37

How to update variables in a class from an activity

I have ImageAnalyzer class for image analysis using cameraX. I need to update variables in class from camera activity.

Code for camera activity:

class CustomCameraActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        viewBinding.currencyHistoryButton.setOnClickListener {
           val intent = Intent(context, CountryPickerActivity::class.java)
           startActivityForResult(intent, 112)
       }
    }


// Code to receive data from activity result which i need to pass to the class for updation

   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       super.onActivityResult(requestCode, resultCode, data)
       if (requestCode == 112) {
           if (resultCode == Activity.RESULT_OK) {
               val result = data?.getStringExtra("COUNTRY")
               Log.e(TAG, "COUNTRY:$result")
           }
           if (resultCode == Activity.RESULT_CANCELED) {
               // Write your code if there's no result
           }
       }
   }

}

code for imageAnalysis class:

class ImageAnalyzer(listener: ImageAnalyzerListener? = null) : ImageAnalysis.Analyzer, ViewModel() {

    private val listeners = ArrayList<ImageAnalyzerListener>().apply { listener?.let { add(it) } }
    
    //value I need to update
    private val country = MutableLiveData<String>("Canada")


}

Upvotes: 0

Views: 38

Answers (1)

z.g.y
z.g.y

Reputation: 6277

Your ImageAnalyzer class is a ViewModel, so assuming you have access to its instance, you would create another read-only live data and observe changes made to it.

class ImageAnalyzer(listener: ImageAnalyzerListener? = null) : ImageAnalysis.Analyzer, ViewModel() {
    
        ...
    
        //value I need to update
        private val _country = MutableLiveData<String>("Canada")

        // only expose a readable state
        val country : LiveData<String> = _country
        
        fun updateCountry(newValue: String) {
            country.value = newValue
        }
    }

Then somewhere in your CustomCameraActivity, assuming you already have an instance of ImageAnalyzer ViewModel

fun someActivityFunction() {
    imageAnalysisVM.updateCountry("Thailand")
}

Now if you want to listen to its changes

fun listenToCountryChanges() {

    imageAnalysisVM.country.observe(viewLifecycleOwner) {
            // react to changes made to the country
    }

}

Upvotes: 1

Related Questions