Use same GPS location code on multiple fragments

Issue

I want to make an application that will include five different fragments. In each fragment I need the GPS location of the device but the purpose will be different.

In order not to implement FusedLocationProviderClient five times for each fragment, I was thinking of doing this once in MainActivity and sending the results to the displayed fragment.

Being a beginner in java programming I ask you for guidance. How can I determine the GPS location of the device and the location is automatically sent (at each update) to the active fragment?

Maybe something like a service? Any sample code will be welcome. Thanks in advance!

Solution

There is a simple solution to this using ViewModel.

The concept is that you initialize a state holder and share the same instance of that holder across your fragments.

The instance of that holder is stored in your activity.

Your ViewModel might look like this

public class MyViewModel extends ViewModel {
    private MutableLiveData<LatLng> location = new MutableLiveData<LatLng>();
    public LiveData<LatLng> getLocation() {
        return location;
    }

    private void setLocation(LatLng value) {
        location.setValue(value)
    }
}

In your activity get the instance of this viewModel. We use the ViewModelProvider factory for this.

private MyViewModel model;

//in your activity onCreate
model = new ViewModelProvider(this).get(MyViewModel.class);

//and from location callback
model.setLocation(latlng)

In all of your fragments you can observe this data

//first get the same instance of your ViewModel onViewCreated
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getLocation().observe(getViewLifecycleOwner(), item -> {
    // Update the UI.
    //will execture everytime new data is set
});

Include required dependency in your app build.gradle

dependencies {
    def lifecycle_version = "2.0.0"

    implementation  "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
}

Learn more about ViewModel here

Answered By – AagitoEx

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published