Soham
Soham

Reputation: 4417

Send message to previous fragment

I have two fragmnent.Say fragment A and fragment B.Now after clicking on certain button in fragment A I am starting fragment B using below code

            getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.framelayout, companyDetailsFragment)
                    .addToBackStack(null)
                    .commit(); 

Now I have another back button in fragment B.After clicking that button I am removing that particular fragment using below code

getFragmentManager().popBackStack()

Now what I want is when the user click on back button I want to pass some certain data to previous fragment A.And the problem is

onStart() method is not getting called,so I am not getting any values. So how to get the data?Any help will be appreciated.

Upvotes: 3

Views: 1232

Answers (2)

Soham
Soham

Reputation: 4417

I am able to solve it.Here is my answer

1.Create an interface

public interface OnButtonPressListener {
    public void onButtonPressed(String msg);
}

2.Implemented this in Fragment B

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            buttonListener = (OnButtonPressListener) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onButtonPressed");
        }
    }

 back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
               buttonListener.onButtonPressed("Message From First Fragment");
            }
        });

3.Used that listener in the Activity class

public class ParentActivity extends FragmentActivity implements OnButtonPressListener { 
@Override
    public void onButtonPressed(String msg) {
        FragmentA Obj=(FragmentA) getSupportFragmentManager().findFragmentById(R.id.framelayout);
        Obj.setMessage(msg);
    }
}

4.Created the method in Fragment A class

public void setMessage(String msg){
       System.out.print("got it");
    }

Got the reference from this .Hope this will help others.If anyone has other good solution please answer this question.

Upvotes: 3

Booger
Booger

Reputation: 18725

You have a few options:

  1. Store the value you want to pass in a globally scoped variable (SharedPrefs, using a singleton accessible from your Application class, etc).

  2. Start a new instance of your Fragment, and include the variable as a Intent Extra.

AFAIK, there is not a way to add extras to a fragment when starting from the stack (you would access this in the onResume() if the variable could be passed).

Upvotes: 0

Related Questions