Search code examples
androidandroid-fragmentsandroid-radiogroup

how to pass a radiogroup value from a fragment to an activity?


how do i get the value from the radiogroup in fragment, i have 1 fragment to display the question and i want to get the value that the user to activity answers, because the next and back button is in the activity, my question from sqlite database

my activity fragment

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    viewPager = findViewById(R.id.view_pager);
    setupViewPager(viewPager);

    back = findViewById(R.id.btnBack);
    next = findViewById(R.id.btnNext);
    back.setOnClickListener(this);
    next.setOnClickListener(this);
}

display Question from frament to activity used ViewPager

 private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(0));, "1");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(1));, "2");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(2);, "3");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(3));, "4");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(4));, "5");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(5);, "6");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(6));, "7");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(7));, "8");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(8));, "9");
        adapter.addFrag(QuestionFragment.newInstance(String.valueOf(9));, "10");
        viewPager.setOffscreenPageLimit(adapter.getCount());
        viewPager.setAdapter(adapter);
    }

button next and Back

@Override
public void onClick(View view) {
    if(view == back){
        mfragmentIndex--;
        viewPager.setCurrentItem(mfragmentIndex);


    }else if(view == next) {
            mfragmentIndex++;
            viewPager.setCurrentItem(mfragmentIndex);

    }
}

class View Pager

class ViewPagerAdapter extends FragmentPagerAdapter{
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitle = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    public void addFrag(Fragment fragment,String title){
        mFragmentList.add(fragment);
        mFragmentTitle.add(title);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return super.getPageTitle(position);
    }
}

my fragment display Question

public static QuestionFragment newInstance(String questionId1) {
    final QuestionFragment fragment = new QuestionFragment();
    final Bundle args = new Bundle();
    args.putString(ARG_QUESTION_ID,questionId1);
    fragment.setArguments(args);
    return fragment;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final String question1 = getArguments().getString(ARG_QUESTION_ID);
    final DBAdapter dbAdapter = new DBAdapter(getContext());
    questionsList = dbAdapter.getAllQuestions();
    currentQuestion = questionsList.get(Integer.parseInt(question1));
    View view = inflater.inflate(R.layout.fragment_question, container, false);
    final RadioGroup grp=view.findViewById(R.id.radioGroup1);

    txtQuestion=view.findViewById(R.id.tvQuestion);
    rbtnA=view.findViewById(R.id.radio0);
    rbtnB=view.findViewById(R.id.radio1);
    rbtnC=view.findViewById(R.id.radio2);
    rbtnD=view.findViewById(R.id.radio3);
    setPertanyaan();
    return view;
}
private void setPertanyaan()
{

    txtQuestion.setText(currentQuestion.getQUESTION());
    rbtnA.setText(currentQuestion.getOptionA());
    rbtnB.setText(currentQuestion.getOptionB());
    rbtnC.setText(currentQuestion.getOptionC());
    rbtnD.setText(currentQuestion.getOptionD());
}

Solution

  • It can be done by creating an interface in the fragment class and then implementing it in the activity.

    Create an interface in the fragment like:-

    // Container Activity must implement this interface
    public interface OnRadioGroupSelectedListener {
        public void onButtonSelected(String value);
    }
    

    Declare the listner object in the fragment class globally:-

    OnRadioGroupSelectedListener mCallback;
    

    The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnRadioGroupSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnRadioGroupSelectedListener");
        }
    }
    

    Now to recieve the callbacks add:-

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
           // if(checkedId==R.id.radio0)  {
          //      mCallback.onButtonSelected(0)
           //  }else if (checkedId==R.id.radio1)  {
           //     mCallback.onButtonSelected(1);
    
           //  }else if (checkedId==R.id.radio2)  {
            //      mCallback.onButtonSelected(2);
    
           //  }else if (checkedId==R.id.radio3)  {
           //     mCallback.onButtonSelected(3);
    
           //  }
         RadioButton radioButton = group.findViewById(checkedId);
    
         mCallback.onButtonSelected(radioButton.getText());
    
    
    });
    

    The callback passes the position of the checked radiobutton to the activity.

    Now in the activity implement the lister ,

    implements QuestionFragment.OnRadioGroupSelectedListener
    

    and override the method to get the selected button position in the activity.

    Note:- you can also change the onButtonSelected(String selectedRadioButtonValue) parametrs as per your requirement.