1

Screen of my app is divided into two fragments ( upper and lower ). Upper fragment is a question(QuizFragmentType1) and lower fragment (QuizFragment) is containing a button "next" which is changing the upper fragment.

How can I get data from upper fragment by pressing the button "next" in the lower fragment?

The problem is in the method checkAnswers(). When I try to get some data from QuizFragmentType1 I can't. For example:

RadioGroup grp = (RadioGroup) getView().findViewById(R.id.radioGroup1);

radioGroup1 is in the layout of QuizFragmentType1 so I can't reach it. I am obviously missing some communication between these two fragments.

Any suggestions?

This is the code:

Lower Fragment (QuizFragment.java)

public class QuizFragment extends BaseFragment implements View.OnClickListener {

List<Question> quesList;
Button butNext;
EditText input_answer;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
int score = 0;
int qid = 0;
private GameActivity activity;
int i = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment_quiz, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
    butNext = (Button) view.findViewById(R.id.button1);
    butNext.setOnClickListener(this);
    Random r = new Random();
    int Low = 1;
    int High = 3;
    int numb = r.nextInt(High - Low) + Low;

    if (numb == 1) {
        ((GameActivity) getActivity()).addFragment(R.id.game,
                new QuizFragmentType1());
    } else if (numb == 2) {
        ((GameActivity) getActivity()).addFragment(R.id.game,
                new QuizFragmentType2());
    }
}

public void randomQuestionType() {
    if (i < 5) {
        Random r = new Random();
        int Low = 1;
        int High = 3;
        int numb = r.nextInt(High - Low) + Low;

        if (numb == 1) {
            ((GameActivity) getActivity()).addFragment(R.id.game,
                    new QuizFragmentType1());
        } else if (numb == 2) {
            ((GameActivity) getActivity()).addFragment(R.id.game,
                    new QuizFragmentType2());
        }
        i++;
    }
    else {
        ((GameActivity) getActivity()).setupFragment(R.id.game,
                new ResultFragment());
    }

}

public void checkAnswers() {
    RadioGroup grp = (RadioGroup) getView().findViewById(R.id.radioGroup1);
    RadioButton answer = (RadioButton) getView().findViewById(
            grp.getCheckedRadioButtonId());

    String input = ((EditText) getView().findViewById(R.id.userInput))
            .getText().toString();

    if (currentQ.getAnswer().equals(answer.getText())) {
        score++;
        Log.d("score", "Your score" + score);

    } else if (currentQ.getAnswer().equals(input)) {
        score++;
        Log.d("score", "Your score" + score);
        input_answer.getText().clear();
    }
}

public void onClick(View v) {
    randomQuestionType();
}

}

Upper Fragment (QuizFragmentType1.java) or (QuizFragmentType2.java)

public class QuizFragmentType1 extends BaseFragment implements SetQuestionView {

static List<Question> quesList;
int qid = 0;
static Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;

float help = 0;
private GameActivity activity;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (this.activity == null)
        this.activity = (GameActivity) activity;
    quesList = Question.getQuestions(this.activity.getCurrentCategory());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment_quiz_type1, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

    Random br = new Random();
    currentQ = quesList.get(br.nextInt(quesList.size()));

    txtQuestion = (TextView) view.findViewById(R.id.textView1);
    rda = (RadioButton) view.findViewById(R.id.radio0);
    rdb = (RadioButton) view.findViewById(R.id.radio1);
    rdc = (RadioButton) view.findViewById(R.id.radio2);

    setQuestionView();

    for (int i = 0; i < quesList.size(); i++) {
        Log.d("Debug", "Pitanje " + i + ": "
                + quesList.get(i).getQuestion());
    }
}
public void setQuestionView() {
    txtQuestion.setText(currentQ.getQuestion());
    rda.setText(currentQ.getOptA());
    rdb.setText(currentQ.getOptB());
    rdc.setText(currentQ.getOptC());
    qid++;
}

}

Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80
mirta
  • 644
  • 10
  • 25

1 Answers1

1

The only way you can do is create a LocalBroadcastManager, a class which can handle communication (interact) for all of your app's components, i.e. activity, fragment, service, etc. Once your Fragment already registered LocalBroadcastManager, it can communicate with your custom IntentFilter. You don't need to register it in the manifest, just register it in the class you need to receive the information from other components.

From the sender class, call:

Intent intent = new Intent("custom-event-name");
intent.putExtra("key", dataToBePassed);// may boolean, String, int, etc.
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

From the receiver, register it inside onCreate() method:

LocalBroadcastManager.getInstance(context).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));

Also, make sure that you need to unregister it inside onDestroy() method:

LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);

Get the information from the receiver Fragment class:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("key");
        Log.d("receiver", "Got message: " + message);
      }
    };

Note: change context with getActivity() if you register it on Fragment. If on Activity, change with this.

For more example, see this post.

Community
  • 1
  • 1
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87