Cyrus the Great
Cyrus the Great

Reputation: 5932

Send callback from activity to fragment

I have a view pager in my Activity. This pager loads 2 fragments (Fragment1 and Fragment2). My Activity have a button for fetching data from server as a list of my pojo class. Fragment1 and Fragment2 contains recyclerView.

My question is How do I refresh Fragment1's recyclerView adapter (from my Activity) when information is fetched in my Activity?

I created an interface in my Activity:

    public interface IloadCallBack {
    void onLoadAdapter(List<Suser> userList);
}

and I have created a setter for this:

    public void setIloadCallBack(IloadCallBack iloadCallBack) {
    this.iloadCallBack = iloadCallBack;
}

and init it:

iloadCallBack.onLoadAdapter(susers);

Now, I have make a reference of activity into my fragment but I think this is wrong!! yes? what can i do?

Upvotes: 2

Views: 6692

Answers (3)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

How can do refresh recyclerView adapter in fragment 1 from my Activity when information fetched at my activity

You do not need the callback mechanism to pass data to fragment, hosted in activity.

Just create a method in fragment refreshList

// in fragment
public void refreshList(List<Suser> userList){
      this.userList.clear();// empty list
      this.userList.addAll(userList);
      notifyDataSetChanged();
}

Keep a global reference to fragment instance and invoke refreshList from where you receive the response.

public class YourActivity...{
    private Fragment fragmentInstance;


    void someMethodReceivedNewList(){
        // where you receive new list in activity
        if(fragmentinstance!=null)
            fragmentinstance.refreshList(userList);

    }

    void someMethodToLoadFragment(){
        fragmentInstance = new YourFragment1();
        ...
    }
}

Upvotes: 3

Whitebear
Whitebear

Reputation: 1791

Communicating from activity to fragment:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article

        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
}

Communicating from fragment to activity:

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

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

    ...
}

Both are taken from https://developer.android.com/training/basics/fragments/communicating.html

Feel free to have a look there, they explain everything very well.

Upvotes: 2

Sachin Rajput
Sachin Rajput

Reputation: 4344

if you want to perform some action when any specific event happens in some other place like if you want to execute any method in your fragment when an event happened in your activity or vice versa, I will suggest you should use EventBus.

https://github.com/greenrobot/EventBus

This is the simple and straightforward solution.

Upvotes: 0

Related Questions