androidkotlinmvvm

Kotin passing arguments to ViewModel from fragment


I work with MVVM and pagination all work fine, but when i pass argument to viewModel the application crash the error

the code for used recycle adapter

    val modelViewModel = ViewModelProvider(this).get(ModelsViewModel(30).javaClass)
    val modelsAdapter = ModelsAdapter(this,requireContext())
    modelViewModel.modelsPageList.observe(viewLifecycleOwner, Observer { models->
        modelsAdapter.submitList(models)
        model_recycle.also {
            it.layoutManager = LinearLayoutManager(requireContext())
            it.setHasFixedSize(true)
            it.adapter = modelsAdapter
        }
    })

the modelView class is named ModelsViewModel here

class ModelsViewModel(args:Int) : ViewModel() {
    private var liveDataSource: MutableLiveData<PageKeyedDataSource<Int,ModelsData>>
    var modelsPageList:LiveData<PagedList<ModelsData>>

    init {
        val modelsDataSourceFactory = ModelsDataSourceFactory(args)
        liveDataSource = modelsDataSourceFactory.getModelsLiveDataSource()
        val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(ModelsDataSource(args).PAGE_SIZE)
            .build()
        modelsPageList = LivePagedListBuilder<Int,ModelsData>(modelsDataSourceFactory, config).build()
    }
}

class of dataSourceFactory is named ModelsDataSourceFactory

class ModelsDataSourceFactory(private val args:Int): DataSource.Factory<Int,ModelsData>() {

    private var modelLiveDataSource:MutableLiveData<PageKeyedDataSource<Int,ModelsData>> = MutableLiveData()

    override fun create(): DataSource<Int, ModelsData> {
        val modelDataSource = ModelsDataSource(args)
        modelLiveDataSource.postValue(modelDataSource)
        return modelDataSource
    }

    fun getModelsLiveDataSource():MutableLiveData<PageKeyedDataSource<Int,ModelsData>>{
        return modelLiveDataSource
    }
} 

last one class dataSource named ModelsDataSource

class ModelsDataSource(args:Int): PageKeyedDataSource<Int, ModelsData>() {
...
}

I try to make second construct for modelView also app crash


Solution

  • Create a factory class for your view model:

     public class ModelsViewModelFactory implements ViewModelProvider.Factory {
        private int args;
    
    
        public ModelsViewModelFactory(int args) {       
            this.args = args;
        }
    
        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            return (T) new ModelsViewModel(args);
        }
    }
    

    And when instantiating the view model, do like this:

    ModelsViewModelFactory factory = new ModelsViewModelFactory(30);    
    ModelsViewModel modelViewModel = ViewModelProvider(this,factory).get(ModelsViewModel.class);
    

    Hope this gives you an idea of how to pass arguments to your viewmodel.