Java – Sends a message to the previous fragment

Sends a message to the previous fragment… here is a solution to the problem.

Sends a message to the previous fragment

I have two fragments. For example, fragment A and fragment B. Now after clicking a button in fragment A, I start using the code below fragment B

                    .replace(, companyDetailsFragment)

Now there is another back button in fragment B. After clicking the button
I’m using the following code to remove that particular fragment


Now what I want is that when the user hits the back button, I want to pass some specific data to the previous fragment A. The question is

The onStart() method wasn’t called, so I didn’t get any value.
So how do you get the data? Any help would be appreciated.


I can solve it, here is my answer

1. Create an interface

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

2. Implemented in Fragment B

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

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

3. Use that listener in the Activity class

public class ParentActivity extends FragmentActivity implements OnButtonPressListener { 
    public void onButtonPressed(String msg) {
        FragmentA Obj=(FragmentA) getSupportFragmentManager().findFragmentById(;

4. Create a method in the Fragment A class

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

From this Get quoted. Hope this will help others. If anyone has other good solution please answer this question.

Related Problems and Solutions