How can I send data between two fragments that are in different activities?

41 views Asked by At

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;
}

}

1

There are 1 answers

3
devmike01 On

Send data from the Quiz1fragment's activity. The HomeActivity is the host of HomeFragment:

Intent intent = new Intent(getBaseContext(), HomeActivity.class);
intent.putExtra("EXTRA_GOAL", goal);
startActivity(intent);

Retrieve the extra from HomeFragment.

    if (requiredActivity() instanceof HomeActivity){
       String goal = requiredActivity().getIntent().getIntExtra("EXTRA_GOAL");
       Log.d("Retrieved: ", ""+goal);
    }