1

When there are some different fragments in a Activity, What way is the best and more safe for communicating between fragments?
I used callback but I passed it by constructors, now I get some crashes.
I think null callbacks are cause of crashes, when application is in background and then user return to application, callback is null.
There is big problem, when I has a lot of fragments in a Activity, implementing callbacks in the Activity is a difficult and confusing way.
I have tested EventBus but my purpose is just one fragment and It's a little harsh, and also may be fragment needs to get data from parent fragment. Do you know a better way?
my structure
I have many fragments A, B, C ,... . When fragment A is updated ,I want to update fragment B too, and this is the same for other fragments , when updating fragment C, D should be updated too and so on.
if I want to use interfaces, I should write many interfaces. Is there any other suggestion?

3 Answers3

1

You can use Bundle class for this.

 Bundle args = new Bundle();
 args.putString("my_value", "hello world");
 Fragment1 fragment1 = new Fragment1();
 fragment1.setArguments(args);

In another fragment to receive the value:

String requiredValue = getArguments().getString("my_value");
realpac
  • 537
  • 6
  • 13
0
if (getActivity() instanceof YourActivityName)
{
       ((YourFragment2Name)getActivity()).variable);
}

//make sure variable in YourFragment2Name should be public.

Mohit Kalia
  • 351
  • 1
  • 6
0

Everything depends upons your expected scenario.

Using Interface 
Using Broadcast Receivers 
Using Container Activity 
Using EventBus or Alternative Libs 
Using Observers (Rx Pattern)

For Interface Communication Please check

public class MyFragment extends Fragment {

    interface FragmentCallback {
       void onClickButton(MyFragment fragment);
    }    

    private FragmentCallback mCallback;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            mCallback.onClickButton(this);
        }
    }
}

And In Activity

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {

    //onCreate



    @Override
    public void onClickButton(MyFragment fragment) {
       // Do your Task
    }
}
Dipendra Sharma
  • 2,404
  • 2
  • 18
  • 35