Home > Blockchain >  How can i share data across multiple fragments in application?
How can i share data across multiple fragments in application?

Time:08-05

I am working on an application where i m taking input from users across multiple fragments under same activity, and then i am sending that data to firebase now how can i achieve that using shared viewmodel, if possible please guide me how can i achieve that, I am completely new to android. Thank You

CodePudding user response:

I'm assuming you want to share data between fragments. One way to do that is through ViewModels

Specifically, you'll need a view model like this:

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;
    }
}

Then you have your fragments:

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

public class ListFragment 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.
        });
    }
}

Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

If you want to know more about this, refer to: https://developer.android.com/topic/libraries/architecture/viewmodel

  • Related