Calling a method in one fragment from another

how to call one fragment to another fragment in android
how to call method from one fragment to another fragment in android kotlin
call fragment method from another activity android
how many ways to call fragment
call fragment method from another class
call fragment method from activity
how to pass data from one fragment to another fragment in android
call method inside fragment from activity

I've been trying for a while already (as well, searching in here) for something to help me to refresh listView in my MainFragment, when a button is pressed in other fragment. Could sommeone explain me how to make it work?

Here's MainFragment with the function (I excluded other functions, since I don't see how they contribute):

public class MainFragment extends Fragment {
public void otherList() {
    SQLite db = new SQLite(getActivity());
    db.open();
    Calendar sCalendar = Calendar.getInstance();
    String day = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK,
            Calendar.LONG, Locale.ENGLISH);
    Cursor c = db.getAllRecords(day);
    Calendar cal = Calendar.getInstance();
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    arrayOfBars.clear();
    if (c.moveToFirst()) {
        do {
            String country = c.getString(0);
            String city = c.getString(1);
            String bar = c.getString(2);
            String timeStart = c.getString(3);

            String[] h = timeStart.split(":");
            int times = Integer.parseInt(h[0]);

            String timeEnd = c.getString(4);
            String[] h2 = timeEnd.split(":");
            int timee = Integer.parseInt(h2[0]);

            String placeLaLo = c.getString(5);
            String description = c.getString(6);
            String likes = c.getString(7);
            String offer = c.getString(8);

            if (hour < (times + 1) || hour < (timee)) {
                getPrefs = PreferenceManager
                        .getDefaultSharedPreferences(MainFragment.this
                                .getActivity());
                boolean lay = getPrefs.getBoolean("boolean", false);
                if (lay == true) {
                    while (times < timee) {
                        timeStart = times + ":" + h[1];
                        times++;
                        timeEnd = times + ":" + h2[1];
                        arrayOfBars.add(new BarObject(country, city, bar,
                                timeStart, timeEnd, placeLaLo, description,
                                likes, offer, bar));
                    }
                } else {
                    arrayOfBars.add(new BarObject(country, city, bar,
                            timeStart, timeEnd, placeLaLo, description,
                            likes, offer, bar));
                }
            }

        } while (c.moveToNext());

        Collections.sort(arrayOfBars, new BarObject.CompST());

        lv2.setAdapter(null);
        adapter = new BarAdapter(getActivity(), arrayOfBars);
        lv2.setAdapter(adapter);
    } else {
        Toast.makeText(getActivity(), "No database found",
                Toast.LENGTH_LONG).show();
    }
    db.close();
}

}

And here's the other fragment:

public class SocialMedia extends Fragment {
ImageButton facebook, twitter, layoutS;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.social_media, container, false);
    layoutS = (ImageButton) view.findViewById(R.id.ibLayout);

    layoutS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences getPrefs = PreferenceManager
                    .getDefaultSharedPreferences(SocialMedia.this
                            .getActivity());
            boolean lay = getPrefs.getBoolean("boolean", false);
            SharedPreferences.Editor e = getPrefs.edit();
            lay = !lay;
            e.putBoolean("boolean", lay);
            e.commit();
                            //Here I want to call otherList() from MainFragment
        }
    });
    return view;
}

}

FragmentManager fm = getFragmentManager(); 
MainFragment fragm = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
fragm.otherList(); 

This code worked best for me. And seems quite easy

how to call method of one fragment from another , Often you will want one Fragment to communicate with another, for example to during its onAttach() lifecycle method and can then call the Interface methods in� All you have to do is implement your activity (calling all those fragments) with FragmentManager.OnBackStackChangeListener and then bind this listener to your FragmentManager object. Now in the implementation of this listener call a method of your fragment you want to call when that fragment is popout of the BackStack like. 1. 2.

In MainFragment class you can do the following code:

private static MainFragment instance = null;

@Override  
public void onCreate(@Nullable Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    instance = this;  
}

public static MainFragment getInstance() {  
    return instance;  
} 

And in SocialMedia class you can call the method as follows:

MainFragment.getInstance().otherList();   

Communicating with Other Fragments, Calling another fragment for result from one fragment. Now in the implementation of this listener call a method of your fragment you want to� You should move the getDetailsReport () out of the fragment and into some sort of data/utility class - then you can call it from both places. Data should be separate from the UI especially if you need to use it in more than one Activity/Fragment.

you should use interface for this. define an interface in OtherFragment class and implement that in your MainActivity and define a public method in your MainFragment for refreshing your ListView and call that method from your MainActivity. here is an example :

public Class OtherFragment extends Fragment implements OnClickListener {

private Communicator communicator;

   ...

public void setCommunicator(Communicator communicator) {
    this.communicator = communicator;
}

@Override
public void onClick(View v) {
   communicator.clicked();
}

   public interface Communicator {
      public void clicked();
   }
}

and in your MainActivity :

public class MainActivity extends Activity implements OtherFragment.Communicator {

   MainFragment mainFragment;

   @Override
   protected void onCreate(Bundle b) {
      ...
      OtherFragment otherFragment = new OtherFragment();
      otherFragment.setCommunicator(this);
      ...
   }

   ...

   @Override 
   public void clicked() {
     mainFragment.updateList();
   }
}

and in your MainFragment :

public class MainFragment extends Fragment {

    ...

    public void updateList() {
        // update list
    }
}

Calling another fragment for result from one fragment., how to call method of one fragment from another fragment class in android. I want to call a method of FragmentB (Class) from a fragmentA I� This example demonstrate about How to pass data from one fragment to another fragment in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

To call a method from another object (a Fragment is an object) you need to have the reference of that object. So if you want to call MainFragment#otherList() from a SocialMedia instance, SocialMedia needs a reference to MainFragment.

For example:

public class SocialMedia {

    private MainFragment mainFragment = null;

    public void setMainFragment(final MainFragment mainFragment) {
        this.mainFragment = mainFragment
    }
}

Then you can use this.mainFragment.otherList().

how to call method of one fragment from another , Why not call functions from the MainActivity directly from the Fragment, callback interface that one fragment (or activity) implements and another can then call. Using the fragment's interface (which is also the safe way to do fragment->activity comm as explained above) you can call a method that's in your fragment from your activity as well if you want to take an action based on your fragment->activity comm. – Kerem Nov 21 '14 at 2:01 Fragments are meant to be reused and set in any Activity.

            // Calling Parent Fragment method from Child Fragment.
        // Child Fragment
        AppCompatActivity activity = (AppCompatActivity) view.getContext();
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        NavigateFragment navigateFragment = (NavigateFragment) fragmentManager.findFragmentById(R.id.fragment_place_dashboard);
        navigateFragment.sayHelloWorld();


        // -- Some method in Parent Fragment(NavigateFragment).
        public void sayHelloWorld(){
            Log.d(TAG, "Hello World.");
        }

Calling between Fragments and Activities ]================== In , Often you will want one Fragment to communicate with another, method and can then call the Interface methods to communicate with the� i have an activity with button on it and when a click i call the fragment with another button on fragment. but when click on fragment's button i cant call a second fragment. this is my source, pretty simple: activity_main.xml:

Communicate with other fragments, In order to replace one fragment with another, the activity's layout includes an your activity, call getSupportFragmentManager() to get a FragmentManager using fragment is similar to adding one, but requires the replace() method instead of� This page will walk through the android FragmentManager and FragmentTransaction example in which we will replace Fragment with another Fragment using Button OnClickListener. To achieve it, first we get the instance of FragmentTransaction using FragmentManager, then call replace method which will accept view container id and new fragment instance.

Build a flexible UI, And if you want to call a fragment from another fragment: How do I destroy/ create fragments in an Android one pager activity from a different fragment in� Now the fragment can deliver messages to the activity by calling the onArticleSelected () method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface. For example, the following method in the fragment is called when the user clicks on a list item.

How to call fragment methods from activity to fragment in Android , The system calls this method to draw the Fragment UI for the first time. The Fragment is replaced or removed, or another operation is modifying the Fragment . One Fragment communicates with the Activity , and the Activity communicates � And if you want to call a fragment from another fragment: FragmentManager fm = getFragmentManager (); MainFragment frag = (MainFragment)fm.findFragmentById (R.id.main_fragment); frag.<specific_function_name> (); 17.9K views.

Comments
  • FragmentManager fm = getFragmentManager(); MainFragment fragem = (MainFragment)fm.findFragmentById(R.id.main_fragment); fragem.otherList();, Worked for me
  • what is R.id.main_fragment? fragment layout or layout which fragment in loaded?"I have fragment in viewpager"
  • @JamaldinSabirjanov have you figured it out? My app just crashes when I use this code...
  • @JMB No, I made the variables "public static" and use them from another fragments.
  • It shows this warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
  • to be honest I will not try to implement it, since I found a simple solution in the mean time. Thank you for the contributed time
  • @KManos What is the simple solution ?
  • I think it's not a good solution to pass a Fragment to another Fragment
  • Didn't work - it just crashed my app. But I did find a simple solution in the mean time.
  • @KManos It crashed probaby because you didn't set the fragment and it's null.
  • @KManos Then you should post your solution so we can all learn :)
  • I think it's against encapsulation and if you use this method, your fragments are no longer modular and you can't use them in some where else in your application.