简体   繁体   中英

How do I set first values to the viewmodel of EditActivity from getIntent

I have a recyclerview containing rows of info about fruits like name, color, weight, description, matching food...

if i click a button it should load those row values into the intent and take me to startActivityForResult: EditActivity.

Well the reason for the viewmodel is to prevent rotation from resetting the values back to the ones from getIntent. The values only get updated to sql in the mainactivity onreturnresultsomething... method.

if i do '''mviewmodel.name = intent.getStringExtra(name,""):''' in mainactivity oncreate, that would just overrite it on rotation just as if there was no viewmodel at all.

I'm thinking of using sharedpreferences, but there's a better way, and androidviewmodel is an antipattern.

so from getintent how do i add default values to viewmodel in editactivity and that it doesnt get set back to that on rotation?

thanks all!

put your values on [SavedStateHandle]: https://developer.android.com/reference/androidx/lifecycle/SavedStateHandle

mviewmodel.savedStateHandle.set("name",name)

before you set the value, check if it is null or not, something like:

if(mviewmodel.savedStateHandle.get("name) == null){
   mviewmodel.savedStateHandle.set("name",name)
}

you can check it from here: https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate

If you are using the current by viewModels or the underlying ViewModelProvider pattern your ViewModel will not be recreated, so you could add it as a constructor parameter.

Check out ViewModelProvider.Factory for how to do that. Additionally if you plan on using Dagger, but you still have parameters, that you'd like to pass in manually you can check out this library: https://github.com/halcyonmobile/ViewModelFactoryGenerator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM