How to use same data in two different fragments

Viewed 469

I want to use data, that i am recieving from API response, in two different fragments.

Right now i have one activity and two fragments.

When app starts, there is API call in first fragment. Then i show results of API response. Also, i want to use the same result in second fragment. Data i want to use stored in List

So, my question is: do i have to make request in first fragment and somehow pass data to second fragment, or there is a way to make request outside fragment, strore result, and then use this result from both fragments?

3 Answers

If You write Your application in MVVM architectural pattern I think You can use Shared ViewModel.
Android docs. Share data between fragments
Stack Overflow: Sharing data between fragments using ViewModel

It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of master-detail fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}


public class MasterFragment extends Fragment {
    private SharedViewModel model;

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        model.getSelected().observe(getViewLifecycleOwner(), { item ->
           // Update the UI.
        });
    }
}

May be i can explain it. You will have to create one class that extends FragmentStateAdapter , then you should create a single class that extends Fragment instead of having multiple classes and a layout.

Create ClassFragmentPagerAdapter like this:

public class ClassFragmentPagerAdapter extends FragmentStateAdapter {

public ClassFragmentPagerAdapter (@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
    super(fragmentManager, lifecycle);
}

@NonNull
@Override
public Fragment createFragment(int position) {
    if (position == 0) {
        return new ClassFragment ();
    }
    return new ClassFragment ();
}


@Override
public int getItemCount() {
    return 2;
}

Then after that create the other ClassFragment that extends Fragment:

public class ClassFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View view = inflater.inflate(R.layout.layout_name, container, false);
    return view;

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //do stuff here
}

Hope it helps! Happy coding:)

There are a few ways to go about this.

The simplest solution to your problem is to use a Singleton. I strongly advise against this idea for many reasons, but most of the time it's the quickest way to get it up and running.

Another solution is to store the data in a member of the activity, and access that via (activity as MyActivity).myData.

Related