-1

I have a fragment in which I'm asking the user to select his team. It opens another fragment and user can select his team. But I'm stuck because unable to send the team details to the previous fragment.

User clicks the button to set home team, select the team from team_select_fragment, but I'm unable to send team details to the first fragment.

Below is the code for mathc_fragment where the user fills match data:

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

    Toolbar toolbar = rootView.findViewById(R.id.nav_toolbar);
    ((PlayerProfileActivity) getActivity()).getSupportActionBar().setTitle("Create Match");

    city_name = rootView.findViewById(R.id.cityNameEditText);
    ground_name = rootView.findViewById(R.id.groundNameEditText);

    setupImageButton(rootView);
    setupNumberOfPlayersButton(rootView);
    setupHalfTimeButton(rootView);

    preferenceConfig = new SharedPreferenceConfig(this.getContext());

    requestQueue = Volley.newRequestQueue(getActivity());

    Button startMatch = rootView.findViewById(R.id.start_match_bn);


    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {
        rootActivity = (PlayerProfileActivity) context;
    } catch (Exception exception) {
        rootActivity = null;
    }
}

private void setupImageButton(final View rootView) {
    //Select Home team
    ImageButton homeTeamImageButton = rootView.findViewById(R.id.homeTeamImageButton);
    homeTeamImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getChildFragmentManager().beginTransaction().add(R.id.create_match_container,new TeamSelect()).commit();
        }
    });

   //select away team
    ImageButton awayTeamImageButton = rootView.findViewById(R.id.awayTeamImageButton);
    awayTeamImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getChildFragmentManager().beginTransaction().add(R.id.create_match_container,new TeamSelect()).commit();
        }
    });
}

This is the code for team_select_fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_team_select, container, false);

        editText = rootView.findViewById(R.id.team_select_search);

        recyclerView = rootView.findViewById(R.id.team_select_recyclerView);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));

        list_items = new ArrayList<>();
        teamSelectAdapter = new TeamSelectAdapter(list_items, getContext());

        recyclerView.setAdapter(teamSelectAdapter);

        teamSelectAdapter.setOnItemClickListener(this);

        loadRecyclerViewData();

        return rootView;
    }

    private void loadRecyclerViewData() {

        stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int success = jsonObject.getInt("success");
                    if(success==1){
                        JSONArray jsonArray = jsonObject.getJSONArray("Teams");
                        for (int i=0; i < jsonArray.length(); i++){
                            JSONObject jsonObject_current = jsonArray.getJSONObject(i);
                            TeamSelectModelClass teamSelectModelClass = new TeamSelectModelClass(
                                    jsonObject_current.getString("team_id"),
                                    jsonObject_current.getString("team_name"),
                                    jsonObject_current.getString("team_logo_url")
                            );
                            list_items.add(teamSelectModelClass);
                        }
                        teamSelectAdapter.notifyDataSetChanged();
                    }else if(success==0){
                        String message = jsonObject.getString("Message");
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) 
        };
        requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }



    @Override
    public void onItemClick(int position) {
        TeamSelectModelClass clickedItem = list_items.get(position);
        String team_id = clickedItem.getTeam_id();
        String team_name = clickedItem.getTeam_name();
        String team_logo = clickedItem.getTeam_logo_url();

    }
Milan Pansuriya
  • 2,521
  • 1
  • 19
  • 33
Prashant Luhar
  • 299
  • 5
  • 19
  • Duplicate: https://stackoverflow.com/questions/24555417/how-to-send-data-from-one-fragment-to-another-fragment?r=SearchResults – kAliert Dec 11 '18 at 06:45
  • 3
    Possible duplicate of [How to send data from one Fragment to another Fragment?](https://stackoverflow.com/questions/24555417/how-to-send-data-from-one-fragment-to-another-fragment) – ADM Dec 11 '18 at 06:48
  • @ADM No bro, I want my second fragment to act as a popup just select a team and return the value to main fragment, the other questions is different from mine. :/ – Prashant Luhar Dec 11 '18 at 06:53
  • you can use interface to return the value to main fragment – Bunny Dec 11 '18 at 06:54
  • What is an `interface`? – Prashant Luhar Dec 11 '18 at 07:09

2 Answers2

0

use following method in your parent Activity(Activity where you are loading your fragments)

    public void changeFragment(Fragment nextFragment, boolean addToBackstack) {
    int containerId = R.id.content_frame;

    FragmentManager fragmentManager = getSupportFragmentManager();
    final FragmentTransaction transaction = fragmentManager
            .beginTransaction();

    if (fragmentManager.findFragmentById(containerId) != null) {
        fragmentName = fragmentManager.findFragmentById(containerId);
    }

    transaction.replace(containerId, nextFragment);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    if (addToBackstack == true) {
        transaction.addToBackStack(fragmentName.getClass().getName());
    }
    currentFragment = nextFragment.getClass().toString();
    transaction.commit();
}

and call this method in your fragments wherever you want as follows

YourFragment yourFragment = new YourFragment ();
final MainActivity mainActivity = (MainActivity) activity;
   mainActivity.changeFragment(yourFragment, true);
Uma Achanta
  • 3,669
  • 4
  • 22
  • 49
0

2 solution : -If you back to the fragment (by create new fragment),create a call back like

A extends Fragment(){

public A setMethod(X a){
this.a = a;
  return this;
}
}

and in fragment B call

new A().setData(yourdata)

Second solution is you just add your data to SharePreference and get it when you return from the other fragment

shadow
  • 114
  • 11