1

I want to move some data from my Mainactivity to a Fragment...which is inside a tab fragment (which handles a SectionPagerAdapter)....which is inside a fragment in Mainactivity2.

I feel its too complicated and cant get it done.

GameEndedActivity (See wrong and correct variable...these are to be transferred)

public class GameEndedActivity extends AppCompatActivity {

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

    int correct = getIntent().getIntExtra("correct", 0);
    int wrong = getIntent().getIntExtra("wrong", 0);
  }
}

TabFragment

public class TabFragment extends Fragment {

    private int tabsCount;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_tab, container, false);

        if(this.getContext() instanceof ChallengeOverviewActivity){
            tabsCount = 2;
        } else {
            tabsCount = 3;
        }
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this.getContext(), getFragmentManager(), tabsCount);
        ViewPager viewPager = view.findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = view.findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        return view;
    }

}

ResultFragment (Transfer data here - wrong and correct variables)

public class ResultDetailsFragment extends Fragment {

  private TextView tvWrong, tvCorrect;
  private AnswerListener answerListener;

  public interface AnswerListener {
    public void correct(int i);
    public void wrong(int i);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_result_details, container, false);
    tvCorrect = view.findViewById(R.id.tvCorrect);
    tvWrong = view.findViewById(R.id.tvWrong);
    return view;

  }

  @Override
  public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    if (context != null) {
      answerListener = (AnswerListener) context;
    }
  }
}
Sagar Balyan
  • 620
  • 6
  • 20

1 Answers1

1

One way to do this is the add arguments to the fragment when you create an instance of it. In your activity when you create the fragment you want to attach you add some arguments to it. These arguments can then be accessed from the fragments onCreate method.

Just do this same thing again when you are in your fragment and create your second one.

Check this answer out which explains more in detail how to do it: https://stackoverflow.com/a/17436739/964887

just_user
  • 11,769
  • 19
  • 90
  • 135