Getting location using LiveData and FusedLocationProviderClient

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












My goal is to get the location when the app starts, and if the user navigates away and comes back, to receive one location update and that's it. I am worried about removing the observer in the getLocationUpdates method.



BoundLocationManager.class



public class BoundLocationManager extends LiveData<Location> 

private static BoundLocationManager instance;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;

public static BoundLocationManager getInstance(Context appContext)
if (instance == null)
instance = new BoundLocationManager(appContext);

return instance;


private BoundLocationManager(final Context appContext)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(appContext);
createLocationRequest();
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>()
@Override
public void onComplete(@NonNull Task<Location> task)
if(task.isSuccessful() && task.getResult() != null)
setValue(task.getResult());
else
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);


);



private void createLocationRequest()
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


LocationCallback mLocationCallback = new LocationCallback()
@Override
public void onLocationResult(LocationResult locationResult)
for (Location location : locationResult.getLocations())
if (location != null)
setValue(location);


;

@Override
protected void onInactive()
super.onInactive();
if (mLocationCallback != null)
mFusedLocationClient.removeLocationUpdates(mLocationCallback);





WeatherFragment.class



private void getLocationUpdates() 
BoundLocationManager.getInstance(getActivity().getApplicationContext()).observe(this, new Observer<Location>()
@Override
public void onChanged(@Nullable Location location)
if (location != null)
getWeather(location.getLatitude(), location.getLongitude());
getAddress(location.getLatitude(), location.getLongitude());
BoundLocationManager.getInstance(getActivity().getApplicationContext()).removeObserver(this);
else
Toast.makeText(getActivity(), "Location is null", Toast.LENGTH_SHORT).show();

);



And finally I use it:



@Override
public void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
requestPermissions(new StringManifest.permission.ACCESS_FINE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);
else
getLocationUpdates();








share|improve this question





















  • Welcome to Code Review! I hope you get great answers.
    – Phrancis
    Mar 20 at 0:31










  • @Phrancis Thank you very much for the encouragement! Have a great day!
    – LieForBananas
    Mar 20 at 1:00
















up vote
2
down vote

favorite












My goal is to get the location when the app starts, and if the user navigates away and comes back, to receive one location update and that's it. I am worried about removing the observer in the getLocationUpdates method.



BoundLocationManager.class



public class BoundLocationManager extends LiveData<Location> 

private static BoundLocationManager instance;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;

public static BoundLocationManager getInstance(Context appContext)
if (instance == null)
instance = new BoundLocationManager(appContext);

return instance;


private BoundLocationManager(final Context appContext)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(appContext);
createLocationRequest();
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>()
@Override
public void onComplete(@NonNull Task<Location> task)
if(task.isSuccessful() && task.getResult() != null)
setValue(task.getResult());
else
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);


);



private void createLocationRequest()
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


LocationCallback mLocationCallback = new LocationCallback()
@Override
public void onLocationResult(LocationResult locationResult)
for (Location location : locationResult.getLocations())
if (location != null)
setValue(location);


;

@Override
protected void onInactive()
super.onInactive();
if (mLocationCallback != null)
mFusedLocationClient.removeLocationUpdates(mLocationCallback);





WeatherFragment.class



private void getLocationUpdates() 
BoundLocationManager.getInstance(getActivity().getApplicationContext()).observe(this, new Observer<Location>()
@Override
public void onChanged(@Nullable Location location)
if (location != null)
getWeather(location.getLatitude(), location.getLongitude());
getAddress(location.getLatitude(), location.getLongitude());
BoundLocationManager.getInstance(getActivity().getApplicationContext()).removeObserver(this);
else
Toast.makeText(getActivity(), "Location is null", Toast.LENGTH_SHORT).show();

);



And finally I use it:



@Override
public void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
requestPermissions(new StringManifest.permission.ACCESS_FINE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);
else
getLocationUpdates();








share|improve this question





















  • Welcome to Code Review! I hope you get great answers.
    – Phrancis
    Mar 20 at 0:31










  • @Phrancis Thank you very much for the encouragement! Have a great day!
    – LieForBananas
    Mar 20 at 1:00












up vote
2
down vote

favorite









up vote
2
down vote

favorite











My goal is to get the location when the app starts, and if the user navigates away and comes back, to receive one location update and that's it. I am worried about removing the observer in the getLocationUpdates method.



BoundLocationManager.class



public class BoundLocationManager extends LiveData<Location> 

private static BoundLocationManager instance;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;

public static BoundLocationManager getInstance(Context appContext)
if (instance == null)
instance = new BoundLocationManager(appContext);

return instance;


private BoundLocationManager(final Context appContext)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(appContext);
createLocationRequest();
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>()
@Override
public void onComplete(@NonNull Task<Location> task)
if(task.isSuccessful() && task.getResult() != null)
setValue(task.getResult());
else
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);


);



private void createLocationRequest()
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


LocationCallback mLocationCallback = new LocationCallback()
@Override
public void onLocationResult(LocationResult locationResult)
for (Location location : locationResult.getLocations())
if (location != null)
setValue(location);


;

@Override
protected void onInactive()
super.onInactive();
if (mLocationCallback != null)
mFusedLocationClient.removeLocationUpdates(mLocationCallback);





WeatherFragment.class



private void getLocationUpdates() 
BoundLocationManager.getInstance(getActivity().getApplicationContext()).observe(this, new Observer<Location>()
@Override
public void onChanged(@Nullable Location location)
if (location != null)
getWeather(location.getLatitude(), location.getLongitude());
getAddress(location.getLatitude(), location.getLongitude());
BoundLocationManager.getInstance(getActivity().getApplicationContext()).removeObserver(this);
else
Toast.makeText(getActivity(), "Location is null", Toast.LENGTH_SHORT).show();

);



And finally I use it:



@Override
public void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
requestPermissions(new StringManifest.permission.ACCESS_FINE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);
else
getLocationUpdates();








share|improve this question













My goal is to get the location when the app starts, and if the user navigates away and comes back, to receive one location update and that's it. I am worried about removing the observer in the getLocationUpdates method.



BoundLocationManager.class



public class BoundLocationManager extends LiveData<Location> 

private static BoundLocationManager instance;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;

public static BoundLocationManager getInstance(Context appContext)
if (instance == null)
instance = new BoundLocationManager(appContext);

return instance;


private BoundLocationManager(final Context appContext)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(appContext);
createLocationRequest();
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>()
@Override
public void onComplete(@NonNull Task<Location> task)
if(task.isSuccessful() && task.getResult() != null)
setValue(task.getResult());
else
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);


);



private void createLocationRequest()
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


LocationCallback mLocationCallback = new LocationCallback()
@Override
public void onLocationResult(LocationResult locationResult)
for (Location location : locationResult.getLocations())
if (location != null)
setValue(location);


;

@Override
protected void onInactive()
super.onInactive();
if (mLocationCallback != null)
mFusedLocationClient.removeLocationUpdates(mLocationCallback);





WeatherFragment.class



private void getLocationUpdates() 
BoundLocationManager.getInstance(getActivity().getApplicationContext()).observe(this, new Observer<Location>()
@Override
public void onChanged(@Nullable Location location)
if (location != null)
getWeather(location.getLatitude(), location.getLongitude());
getAddress(location.getLatitude(), location.getLongitude());
BoundLocationManager.getInstance(getActivity().getApplicationContext()).removeObserver(this);
else
Toast.makeText(getActivity(), "Location is null", Toast.LENGTH_SHORT).show();

);



And finally I use it:



@Override
public void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
requestPermissions(new StringManifest.permission.ACCESS_FINE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);
else
getLocationUpdates();










share|improve this question












share|improve this question




share|improve this question








edited Mar 20 at 0:10









Jamal♦

30.1k11114225




30.1k11114225









asked Mar 20 at 0:06









LieForBananas

1133




1133











  • Welcome to Code Review! I hope you get great answers.
    – Phrancis
    Mar 20 at 0:31










  • @Phrancis Thank you very much for the encouragement! Have a great day!
    – LieForBananas
    Mar 20 at 1:00
















  • Welcome to Code Review! I hope you get great answers.
    – Phrancis
    Mar 20 at 0:31










  • @Phrancis Thank you very much for the encouragement! Have a great day!
    – LieForBananas
    Mar 20 at 1:00















Welcome to Code Review! I hope you get great answers.
– Phrancis
Mar 20 at 0:31




Welcome to Code Review! I hope you get great answers.
– Phrancis
Mar 20 at 0:31












@Phrancis Thank you very much for the encouragement! Have a great day!
– LieForBananas
Mar 20 at 1:00




@Phrancis Thank you very much for the encouragement! Have a great day!
– LieForBananas
Mar 20 at 1:00










1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










Let me explain how to work with LiveData - ViewModel and Activity.



Right now your BoundLocationManager looks good. I'd recommend not to make it's singleton. And also not consuming it directly in your UI (in this case WeatherFragment) code.



It's highly recommended to keep LiveData in ViewModel and your ViewModel will provide it the UI.



Also if you use LiveData, then never worry about removing the observer. It's done automatically for you.



Let me know if you still have some queries.






share|improve this answer





















  • You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
    – LieForBananas
    Mar 25 at 16:10











  • Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
    – Akshay Chordiya
    Mar 25 at 16:18










  • Perfect! Thanks a lot for the help!
    – LieForBananas
    Mar 25 at 16:30










Your Answer




StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: false,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);








 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189987%2fgetting-location-using-livedata-and-fusedlocationproviderclient%23new-answer', 'question_page');

);

Post as a guest






























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










Let me explain how to work with LiveData - ViewModel and Activity.



Right now your BoundLocationManager looks good. I'd recommend not to make it's singleton. And also not consuming it directly in your UI (in this case WeatherFragment) code.



It's highly recommended to keep LiveData in ViewModel and your ViewModel will provide it the UI.



Also if you use LiveData, then never worry about removing the observer. It's done automatically for you.



Let me know if you still have some queries.






share|improve this answer





















  • You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
    – LieForBananas
    Mar 25 at 16:10











  • Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
    – Akshay Chordiya
    Mar 25 at 16:18










  • Perfect! Thanks a lot for the help!
    – LieForBananas
    Mar 25 at 16:30














up vote
2
down vote



accepted










Let me explain how to work with LiveData - ViewModel and Activity.



Right now your BoundLocationManager looks good. I'd recommend not to make it's singleton. And also not consuming it directly in your UI (in this case WeatherFragment) code.



It's highly recommended to keep LiveData in ViewModel and your ViewModel will provide it the UI.



Also if you use LiveData, then never worry about removing the observer. It's done automatically for you.



Let me know if you still have some queries.






share|improve this answer





















  • You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
    – LieForBananas
    Mar 25 at 16:10











  • Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
    – Akshay Chordiya
    Mar 25 at 16:18










  • Perfect! Thanks a lot for the help!
    – LieForBananas
    Mar 25 at 16:30












up vote
2
down vote



accepted







up vote
2
down vote



accepted






Let me explain how to work with LiveData - ViewModel and Activity.



Right now your BoundLocationManager looks good. I'd recommend not to make it's singleton. And also not consuming it directly in your UI (in this case WeatherFragment) code.



It's highly recommended to keep LiveData in ViewModel and your ViewModel will provide it the UI.



Also if you use LiveData, then never worry about removing the observer. It's done automatically for you.



Let me know if you still have some queries.






share|improve this answer













Let me explain how to work with LiveData - ViewModel and Activity.



Right now your BoundLocationManager looks good. I'd recommend not to make it's singleton. And also not consuming it directly in your UI (in this case WeatherFragment) code.



It's highly recommended to keep LiveData in ViewModel and your ViewModel will provide it the UI.



Also if you use LiveData, then never worry about removing the observer. It's done automatically for you.



Let me know if you still have some queries.







share|improve this answer













share|improve this answer



share|improve this answer











answered Mar 25 at 15:47









Akshay Chordiya

1362




1362











  • You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
    – LieForBananas
    Mar 25 at 16:10











  • Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
    – Akshay Chordiya
    Mar 25 at 16:18










  • Perfect! Thanks a lot for the help!
    – LieForBananas
    Mar 25 at 16:30
















  • You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
    – LieForBananas
    Mar 25 at 16:10











  • Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
    – Akshay Chordiya
    Mar 25 at 16:18










  • Perfect! Thanks a lot for the help!
    – LieForBananas
    Mar 25 at 16:30















You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
– LieForBananas
Mar 25 at 16:10





You save me everywhere :) everything is perfectly clear, but, I remove the observer because I only want to receive one update from the location service, otherwise everytime the user moves the location will be updated. That is why I unregister the observer straight away.
– LieForBananas
Mar 25 at 16:10













Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
– Akshay Chordiya
Mar 25 at 16:18




Haha no problem at all. Take a look at github.com/googlesamples/android-architecture/blob/…, I think it's useful if you want to receive one update.
– Akshay Chordiya
Mar 25 at 16:18












Perfect! Thanks a lot for the help!
– LieForBananas
Mar 25 at 16:30




Perfect! Thanks a lot for the help!
– LieForBananas
Mar 25 at 16:30












 

draft saved


draft discarded


























 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189987%2fgetting-location-using-livedata-and-fusedlocationproviderclient%23new-answer', 'question_page');

);

Post as a guest













































































Popular posts from this blog

Greedy Best First Search implementation in Rust

Function to Return a JSON Like Objects Using VBA Collections and Arrays

C++11 CLH Lock Implementation