<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Steve Kamau on Medium]]></title>
        <description><![CDATA[Stories by Steve Kamau on Medium]]></description>
        <link>https://medium.com/@stevekamau72?source=rss-58e0fcf2126------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oamPV1z2xClIRQj6kTpiPQ.jpeg</url>
            <title>Stories by Steve Kamau on Medium</title>
            <link>https://medium.com/@stevekamau72?source=rss-58e0fcf2126------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:46:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevekamau72/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to fix null lastLocation from FusedLocationProviderClient]]></title>
            <link>https://medium.com/@stevekamau72/how-to-fix-null-lastlocation-from-fusedlocationproviderclient-6629280a90b4?source=rss-58e0fcf2126------2</link>
            <guid isPermaLink="false">https://medium.com/p/6629280a90b4</guid>
            <category><![CDATA[location]]></category>
            <category><![CDATA[google-play-services]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Steve Kamau]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 07:24:47 GMT</pubDate>
            <atom:updated>2024-01-04T07:25:30.586Z</atom:updated>
            <content:encoded><![CDATA[<p>While i was working on an app that needed user’s current location, naturally i went through <a href="https://developer.android.com/develop/sensors-and-location/location/retrieve-current">Google’s documentation</a> on how to approach this and best latest practices.</p><p>What caught my eye was this particular block:</p><blockquote>The location object may be null in the following situations:</blockquote><blockquote>1. Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.</blockquote><blockquote>2. The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.</blockquote><blockquote>3. Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see <a href="https://developer.android.com/training/location/receive-location-updates">Receiving Location Updates</a>.</blockquote><p>And true to this, i noticed when i manually turned off location from device settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*F9gQzwZYc0p-DQYLFDTBnA.png" /></figure><p>And lauching my app to retrieve user’s last known location, i was getting null location object. As explained in the documentation above, location cache was cleared off when i turned it off, and it needs some time before being able to retrieve location again. Time that our users don’t have.</p><p>The solution to “force” retrival of this location for such cases led me down this path:</p><pre>private fun getDeviceLocation() {<br>  val fusedLocationProviderClient =<br>                LocationServices.getFusedLocationProviderClient(requireContext())<br>  val locationResult = fusedLocationProviderClient.lastLocation<br>  locationResult.addOnCompleteListener(requireActivity()) { task -&gt;<br>    if (task.isSuccessful) {<br>      // i check for the result here, if null it means the location object is null<br>      if (task.result == null) {<br>        // so we need to find a different way to force this retrieval<br>        handleNewLocation()<br>        return@addOnCompleteListener<br>       }<br>       // do what you want with task.result<br>     } else {<br>       Timber.tag(TAG).d(&quot;Current location is null. Using defaults.&quot;)<br>       handleNewLocation()<br>     }<br>    }<br> }</pre><pre>private fun handleNewLocation() {<br>        val fusedLocationProviderClient =<br>            LocationServices.getFusedLocationProviderClient(requireContext())<br>        lifecycleScope.launch(Dispatchers.IO) {<br>            // Becareful when using Priority.PRIORITY_HIGH_ACCURACY since it drains battery more<br>            // See documentation https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest<br>            val priority = Priority.PRIORITY_HIGH_ACCURACY<br>            val result = fusedLocationProviderClient.getCurrentLocation(<br>                priority,<br>                CancellationTokenSource().token,<br>            ).await()<br>            result?.let { fetchedLocation -&gt;<br>                withContext(Dispatchers.Main) {<br>                    // do what you want with fetchedLocation<br>                }<br>            }<br>        }<br>    }</pre><p>Things to note here:</p><ol><li>I have abstracted checking for permissions, you need to check too</li><li>This code uses <a href="https://mvnrepository.com/artifact/com.google.android.gms">com.google.android.gms</a>:21.0.1</li><li>Priority set to Priority.PRIORITY_HIGH_ACCURACY but check the <a href="https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest">documentation</a> so you don’t misuse this leading to device battery drain.</li></ol><p>That’s it! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6629280a90b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>