Pass data from Fragments to Activity

0

I have an application with a main activity and inside it there is a viewpager with fragments generated by a list and a floating button. What I want is that by clicking this button I can return data of all fragments generated for this activity. But it always returns only the data from the last fragment.

    public class QuestionFragment extends Fragment {
    private TextView tvQuestionNumber;
    private TextView tvQuestion;
    private RadioGroup rgAnswer;
    private RadioButton rb1, rb2, rb3, rb4, rb5;
    private ImageView ivPhoto;
    private Question question;
    private FloatingActionButton fab;

    // declaração da interface de comunicação
    public interface communication {

        // aqui, um ou mais métodos de comunicação
        void setData(int data); // por exemplo, este método retorna a idade inserida no fragment
    }

    /* variável que representa quem vai receber a atualização dos dados, no caso a activity principal, que vai implementar a interface de comunicação */
    private communication listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof communication) {
            listener = (communication) activity;
        } else {
            throw new RuntimeException("Activity deve implementar ExemploFragment.Communication");
        }
    }

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

        View view = inflater.inflate(R.layout.question_fragment, container, false);

        tvQuestionNumber = (TextView) view.findViewById(R.id.tv_question_number);
        tvQuestion = (TextView) view.findViewById(R.id.tv_question);
        rgAnswer = (RadioGroup) view.findViewById(R.id.rg_answer);

        ivPhoto = (ImageView) view.findViewById(R.id.iv_photo);

        rb1 = (RadioButton) view.findViewById(R.id.rb_option_1);
        rb2 = (RadioButton) view.findViewById(R.id.rb_option_2);
        rb3 = (RadioButton) view.findViewById(R.id.rb_option_3);
        rb4 = (RadioButton) view.findViewById(R.id.rb_option_4);
        rb5 = (RadioButton) view.findViewById(R.id.rb_option_5);

        fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final Bundle data = getArguments();

        if (savedInstanceState != null && savedInstanceState.getParcelable("question") != null) {
            question = savedInstanceState.getParcelable("question");
        } else {
            question = ((MainActivity) getActivity()).questionObject(data.getInt("position"));
        }

        tvQuestionNumber.setText("Questão " + (data.getInt("position") + 1) + ":");
        tvQuestion.setText(question.getQuestion());

        if (question.getUrl() != null) {
            float scale = getActivity().getResources().getDisplayMetrics().density;
            int width = getActivity().getResources().getDisplayMetrics().widthPixels - (int)(14 * scale + 0.5f);
            int height = (width / 16) * 9;

            Glide
                    .with(getActivity())
                    .load(question.getUrl())
                    .centerCrop()
                    .crossFade()
                    .into(ivPhoto);

            ivPhoto.getLayoutParams().height = height;
            ivPhoto.setVisibility(View.VISIBLE);
        }

        rb1.setText(question.getA());
        rb2.setText(question.getB());
        rb3.setText(question.getC());
        rb4.setText(question.getD());
        rb5.setText(question.getE());

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id = rgAnswer.getCheckedRadioButtonId();

                listener.setData(id);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("question", question);
    }
}

This is the fragment code.

    
asked by anonymous 15.05.2017 / 03:41

1 answer

1

You can use events. link

In your fragment you declare an interface and implement this interface in your Activity. When creating your fragment, create a method that expects the event as a parameter, pass the reference of your activity to this fragment (since your activity implements this event).

    
18.05.2017 / 16:29