---
# System prepended metadata

title: Pass Variables to ViewModel

---

# Pass Variables to ViewModel

## Introduction 
We will have two fragments sharing same viewModel. So if there is an update in the information used by both, both will update automatically.

## Coding Part
We will need to make a **viewModel, viewmodel factory** to achieve this.

**ViewModel**
```java===
package com.studyappjava.viewmodel;

import android.util.Log;
import androidx.lifecycle.ViewModel;

public class MainVM extends ViewModel {
    public MainVM(String input){
        Log.d("VM Factory", input);
    }
}
```

**ViewModel Factory**
```java===
package com.studyappjava;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.studyappjava.viewmodel.MainVM;

@SuppressWarnings("unchecked")
public class ViewModelFactory implements ViewModelProvider.Factory {

    private String textDisplay;

    public ViewModelFactory(String input){
        this.textDisplay = input;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if(modelClass.isAssignableFrom(MainVM.class)){
            return ((T) new MainVM(this.textDisplay));
        }
        throw new IllegalArgumentException("VM not found");
    }
}
```

**Activity**
```java===
package com.studyappjava.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import com.studyappjava.R;
import com.studyappjava.ViewModelFactory;
import com.studyappjava.databinding.ActivityFactoryVmBinding;
import com.studyappjava.viewmodel.MainVM;

public class FactoryVMActivity extends AppCompatActivity {

    private ActivityFactoryVmBinding dealBind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initVM();
    }

    private void initView(){
        View dealView = LayoutInflater.from(this).inflate(R.layout.activity_factory_vm, null);
        dealBind = ActivityFactoryVmBinding.bind(dealView);
        setContentView(dealBind.getRoot());
    }

    private void initVM(){
        ViewModelFactory vmFactory = new ViewModelFactory("Pass argument to VM Successful through VM Factory!");
        ViewModelProviders.of(this, vmFactory).get(MainVM.class);
    }
}

```