Search code examples
androidkotlinandroid-fragmentsandroid-databindingandroid-viewmodel

Pass Navigation fragments arguments to View Model class


I am new to android app development. Please help. I want to get navigation fragment arguments in my view model class directly. I am using data-binding.

Here is my nav fragments argument

<fragment>
          ......
           ..
        <action
            android:id="@+id/action_update_to_listOfStudentFragment"
            app:destination="@id/list_fragment" />
        <argument
            android:name="currentStudent"
            app:argType="com.example.school.model.Student" />
    </fragment>

When I click on my recycler view item I pass the argument object with navigation action. So I set on click listener in adapters onbind function. I am passing student objects as arguments.

holder.itemLayoutBinding.root.setOnClickListener {
        val action = ListOfStudentFragmentDirections.actionListOfStudentFragmentToUpdate(currentStudent)
        holder.itemLayoutBinding.root.findNavController().navigate(action)
    }

My View Model is here. I want to know another thing: I am using AndroidViewModel here for database context. Is there any other way to avoid AndroidViewModel? I want to use ViewModel but the view model does not provide context.

    class MainModleView(application: Application) : AndroidViewModel(application) {

val getAllStudentData: LiveData<List<Student>>
    val repository: Repository

    val inputName = MutableLiveData<String>()
    val inputAge = MutableLiveData<String>()

    init {
        val studentDao: StudentDao = StudentDatabase.getAllData(application).studentDao()
        repository = Repository(studentDao)
        getAllStudentData = repository.getAllData

    }

So in View-Model's live data, I want to set the inputName and inputAge value from fragments arguments. Here is a sample of what I want.

inputName.value = fragmentsarugments.name //arguments pass a model object from recyclerview on click function
inputAge.value = fragmentsarugments.age

Please give me a solution. I only want to get fragment's argument in my ViewModel.


Solution

  • I think it's very easy. Only one line code and do your job.

    class YourModleView(
        savedStateHandle: SavedStateHandle
    ) : ViewModel()
    

    Here savedstatehandle will provide your navigation fragment arguments. Your argument type is Studnet class.

    val myObject:Student = savedStateHandle["argument name in navigation"]
    

    Now from your fragment action pass the arguments object. You will get every passing argument object with savedstatehandle.

    myObject.something 
    

    You will get your passing object.