Friday, March 19, 2021

[android ]Pass data from first fragment to second fragment using MVVM pattern

Let's suppose we have two fragments in a single activity. If we are using MVVM android design patter then we need to familiar about view model class.

1.  you need to create a fragment 1. In this case we have fragment-1 name is UserProfileFragment. 

You can pass user profile info to another fragment when user is clicked on next button on the screen.

class UserProfileFragment : BaseFragment() {
private lateinit var model: UserViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProvider(this).get(UserViewModel::class.java)
} ?: throw Exception("Invalid Fragment")

}
R.id.button_next -> {
//Code statements
if(validateUserDetails()) {
var first_name : String =edit_firstname.getText().toString();
var last_name : String =edit_lastname.getText().toString();
var dob : String =edit_date.getText().toString();
val user = UserData(first_name, last_name, dob)
model.setUserdata(user)

}
}
}
2. You need to create the view model class to keep the object state.
class UserViewModel : ViewModel()  {

var data = MutableLiveData<UserData>()


fun setUserdata(user: UserData) {
data.value = user;
}
}

3.  you need to create a fragment-2 . In this case we have fragment-2 name is UserDetailFragment

We can receive the user profile info in fragment-2 which is coming from fragment "UserProfileFragment" when user is clicked on next button on the screen.

class UserDetailFragment : BaseFragment(){
private val TAG = UserDetailFragment::class.java.name
private lateinit var tv_firstname : TextView
private lateinit var tv_lastname : TextView
private lateinit var tv_user_age : TextView
private lateinit var button_previous: TextView;

companion object {
fun newInstance() = UserDetailFragment()
}
private lateinit var model: UserViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

}

override fun getLayoutId(): Int {
return R.layout.fragment_userdetail
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

tv_firstname = view.findViewById(R.id.tv_firstname)
tv_lastname = view.findViewById(R.id.tv_lastname)
tv_user_age = view.findViewById(R.id.tv_user_age)
button_previous = view.findViewById(R.id.button_previous)
button_previous.setOnClickListener(this)
model = activity?.run {
ViewModelProvider(this).get(UserViewModel::class.java)
} ?: throw Exception("Invalid Activity")
model.data.observe(this, Observer<UserData> { item ->
// Update the UI
Log.i(TAG, "onCreate :: start " +item.first_name)
tv_firstname.setText("First Name:" +item.first_name);
tv_lastname.setText("Last Name: "+item.last_name);
tv_user_age.setText("Age: "+ageCalc(item.date_of_birth).toString());
})
}

No comments:

Post a Comment