I want to send the variable 'goal' from Quiz1Fragment to HomeFragment, even though they are in different activities. I attempted to use a SharedViewModel, but the goal isn't assigned correctly. Can someone help figure it out?
Quiz1fragment
public class Quiz1Fragment extends Fragment {
private SharedViewModel sharedViewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quiz1, container, false);
RadioGroup radioGroup = view.findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int goal = 0;
if (checkedId == R.id.lose) {
goal = 100;
} else if (checkedId == R.id.gain) {
goal = 200;
} else if (checkedId == R.id.maintain) {
goal = 300;
}
sharedViewModel.setSelectGoal(goal);
}
});
return view;
}
}
HomeFragment
public class HomeFragment extends Fragment {
TextView textView;
SharedViewModel sharedViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
textView = view.findViewById(R.id.textViewCalories);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
Integer goal = sharedViewModel.getSelectedGoal().getValue();
textView.setText(String.valueOf(goal));
return view;
}
}
Send data from the
Quiz1fragment
's activity. TheHomeActivity
is the host ofHomeFragment
:Retrieve the extra from
HomeFragment
.