Search code examples
androidandroid-fragmentssearchview

Refresh a Fragment from mainactivity


I have an Activity with three tabs and three Fragments. First Fragment shows the list of song titles and the second tab displays the selected song. The details of the songs is coming from a database. I am implementing SearchView feature so that whatever search text user enters, only those songs should be displayed in the index.

This is exactly like the way phone book work in our devices.

enter image description here

I'm not able to understand how to refresh the first Fragment when the search query changes. I'm basically looking for the method that I can call to refresh the first Fragment.


Solution

  • Got my answer here Android refresh a fragment list from its parent activity as suggested by @Prem. Works perfectly fine for me.

    Its is achievable by making an interface

    MainActivity.java

    public class MainActivity extends Activity {
    
    public FragmentRefreshListener getFragmentRefreshListener() {
        return fragmentRefreshListener;
    }
    
    public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
        this.fragmentRefreshListener = fragmentRefreshListener;
    }
    
    private FragmentRefreshListener fragmentRefreshListener;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
        Button b = (Button)findViewById(R.id.btnRefreshFragment);
    
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(getFragmentRefreshListener()!=null){
                    getFragmentRefreshListener().onRefresh();
                }
            }
        });
    
    
    }
    
    
    public interface FragmentRefreshListener{
        void onRefresh();
    }}
    

    MyFragment.java

    public class MyFragment extends Fragment {
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = null; // some view
    
        /// Your Code
    
    
        ((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
            @Override
            public void onRefresh() {
    
                // Refresh Your Fragment
            }
        });
    
    
        return v;
    }}