Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a callback between Activity and Fragment?

I have this interface in my activity.

public interface LogoutUser {
    void logout();
}

My fragment implements this interface, so in my fragment, I have this:

@Override
public void logout() {
    // logout
}

In my activity I call

mLogoutUser.logout();

Where mLogoutUser is of the type LogoutUser interface.

My issue is the mLogoutUser object that is null. How can initialize it?

Thank you!

like image 876
androidevil Avatar asked May 10 '13 21:05

androidevil


1 Answers

As I said in my comment, I resolved this issue using onAttach method in my fragment, but in this way you have to have the callback field (mLogoutUser in this case) declared in the fragment, and initialize it this way:

public class MyFragment extends ListFragment {
    LogoutUser mLogoutUser;

    // Container Activity must implement this interface
    public interface LogoutUser {
        public void logout();
    }

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

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mLogoutUser = (LogoutUser) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement LogoutUser");
        }
    }

    ...
}

More info in Communicating with Other Fragments.


But if your case is the field declared in the activity, you can use the onAttachFragment method from your activity to initialize your listener field this way:

@Override
public void onAttachFragment(Fragment fragment) {
    super.onAttachFragment(fragment);

    mLogoutUser = (LogoutUser) fragment;
}

Also, you can use an event bus to make this communication between fragments and activities. An option is the Otto library, from Square.

like image 98
androidevil Avatar answered Oct 02 '22 23:10

androidevil