Home > OS >  how to pass data between activities forward and backward, android, kotlin
how to pass data between activities forward and backward, android, kotlin

Time:02-11

let's say my application has 4 activities (A -> B -> C -> D) when going forward, activity A pass a data value called category to activity B and then activity B pass category and also and data value called level and both used in activity D to get data from firebase realtime database. but when the user goes back to activity C and tries to go again to D data passed from A (category) is now null. so data can't retrieve from firebase. my question is how can I solve this situation.? "I pass data using Intent by putting extras." are there any other ways?

CodePudding user response:

you could use startactivityforresult and set a result intent which includes the data you want to pass back https://developer.android.com/training/basics/intents/result

CodePudding user response:

You can use a shared ViewModel. Viewmodels are lifecycle-aware components. Data in ViewModels does not disappear when activity changes

Save your data (category,level) in ViewModel like this :

private val _categoryValue =
    MutableLiveData<CategoryType>()
val categoryValue: 
LiveData<ResponseState<CategoryType> =
    _categoryValue

And update your data in activity like this:

vm.categoryValue.value = newCategoryValue

If you are using binding etc. observe and do stuff with your data like this:

vm.deleteFileResponse.observe(this){ category ->
  //Do stuff
 }
  • Related