Get user's current location - Kotlin - android

Guys, I am trying to get a user location but there is something wrong, when I run my app there is no player icon and the location is wrong - it still shows lat = 0.0, lon = 0.0. I don't use an emulator, I test app on my mobile phone (Android 4.4.2 if it matters). Please take a look at my code maybe I just can't see a mistake. Thank you in advance!
class MapsActivity : FragmentActivity(), OnMapReadyCallback {
private var mMap: GoogleMap? = null
private val USER_LOCATION_REQUEST_CODE = 1000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
requestLocationPermission()
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
}
//ask permission
private fun requestLocationPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
USER_LOCATION_REQUEST_CODE
)
}
}
}
fun GetPlayerLocation() {
Toast.makeText(this, "User location access on", Toast.LENGTH_LONG).show()
var playerLocation = PlayerLocationListener()
var locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3, 3f, playerLocation)
var mythread = myThread()
mythread.start()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
USER_LOCATION_REQUEST_CODE -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GetPlayerLocation()
} else {
Toast.makeText(this, "We cannot access to your location", Toast.LENGTH_LONG).show()
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
var location: Location? = null
// Get player location
inner class PlayerLocationListener : LocationListener {
constructor() {
location = Location("Start")
location!!.latitude = 0.0
location!!.longitude = 0.0
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
}
override fun onProviderEnabled(p0: String?) {
}
override fun onProviderDisabled(p0: String?) {
}
override fun onLocationChanged(p0: Location?) {
location = p0
}
}
inner class myThread : Thread {
constructor() : super(){
}
override fun run() {
while (true) {
try {
runOnUiThread {
mMap!!.clear()
val sydney = LatLng(location!!.latitude, location!!.longitude)
mMap!!.addMarker(
MarkerOptions().position(sydney).title("Hi!")
.snippet("Let's go!")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.player)))
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 14f))
}
Thread.sleep(1000)
} catch (ex: Exception) {
}
}
}
}
}
`

try this way
implement in gradle these dependency
implementation 'com.google.android.gms:play-services:11.4.0'
implementation 'com.google.android.gms:play-services-maps:11.4.0'
uses permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
create a locationListener interface
interface locationListener {
fun locationResponse(locationResult: LocationResult)
}
then create a Location.kt class
class Location (var activity: AppCompatActivity, locationListener: locationListener){
private val permissionFineLocation=android.Manifest.permission.ACCESS_FINE_LOCATION
private val permissionCoarseLocation=android.Manifest.permission.ACCESS_COARSE_LOCATION
private val REQUEST_CODE_LOCATION=100
private var fusedLocationClient: FusedLocationProviderClient?=null
private var locationRequest: LocationRequest?=null
private var callbabck: LocationCallback?=null
init {
fusedLocationClient= FusedLocationProviderClient(activity.applicationContext)
inicializeLocationRequest()
callbabck=object: LocationCallback(){
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
locationListener.locationResponse(p0!!)
}
}
}
private fun inicializeLocationRequest() {
locationRequest= LocationRequest()
locationRequest?.interval=50000
locationRequest?.fastestInterval=5000
locationRequest?.priority=LocationRequest.PRIORITY_HIGH_ACCURACY
}
private fun validatePermissionsLocation():Boolean{
val fineLocationAvailable= ActivityCompat.checkSelfPermission(activity.applicationContext, permissionFineLocation)== PackageManager.PERMISSION_GRANTED
val coarseLocationAvailable=ActivityCompat.checkSelfPermission(activity.applicationContext, permissionCoarseLocation)==PackageManager.PERMISSION_GRANTED
return fineLocationAvailable && coarseLocationAvailable
}
private fun requestPermissions(){
val contextProvider=ActivityCompat.shouldShowRequestPermissionRationale(activity, permissionFineLocation)
if(contextProvider){
Toast.makeText(activity.applicationContext, "Permission is required to obtain location", Toast.LENGTH_SHORT).show()
}
permissionRequest()
}
private fun permissionRequest(){
ActivityCompat.requestPermissions(activity, arrayOf(permissionFineLocation, permissionCoarseLocation), REQUEST_CODE_LOCATION)
}
fun onRequestPermissionsResult(requestCode:Int, permissions:Array<out String>, grantResults:IntArray){
when(requestCode){
REQUEST_CODE_LOCATION->{
if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
getLocation()
}else{
Toast.makeText(activity.applicationContext, "You did not give permissions to get location", Toast.LENGTH_SHORT).show()
}
}
}
}
fun stopUpdateLocation(){
this.fusedLocationClient?.removeLocationUpdates(callbabck)
}
fun inicializeLocation(){
if (validatePermissionsLocation()){
getLocation()
}else{
requestPermissions()
}
}
#SuppressLint("MissingPermission")
private fun getLocation() {
validatePermissionsLocation()
fusedLocationClient?.requestLocationUpdates(locationRequest, callbabck, null)
}
}
usage
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
var location: Location?=null
private var mMap: GoogleMap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
location= Location(this, object :locationListener{
override fun locationResponse(locationResult: LocationResult) {
mMap?.clear()
val sydney = LatLng(locationResult.lastLocation.latitude, locationResult.lastLocation.longitude)
mMap?.addMarker(MarkerOptions().position(sydney).title("Hi").snippet("Let's go!"))
mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 14f))
}
})
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
location?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onStart() {
super.onStart()
location?.inicializeLocation()
}
override fun onPause() {
super.onPause()
location?.stopUpdateLocation()
}
}
I hope this help you

Related

Geofence not detecting when I enter the area

In my app my geofence does not update my firebase database when I enter the area. I made sure my code for updating the database works so that is not the problem. Also, when I enter the geofence my activity crashes. I’m going to add all my code for getting my location, the geofence and my broadcast.
Maps activity
class PricklyMapsActivity : AppCompatActivity(), OnMapReadyCallback {
lateinit var toggle: ActionBarDrawerToggle
//location
private lateinit var fusedLocatonClient: FusedLocationProviderClient
private lateinit var myLatlng: LatLng
private lateinit var currentLocation: Location
private val permissionId = 5
//Map
private lateinit var map: GoogleMap
private lateinit var binding: ActivityPricklyMapsBinding
//Goefence
private var gadgetQ = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q
private lateinit var geoClient: GeofencingClient
var geofenceList: MutableList<Geofence> = mutableListOf()
//firebase
private lateinit var database: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPricklyMapsBinding.inflate(layoutInflater)
setContentView(binding.root)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
fusedLocatonClient = LocationServices.getFusedLocationProviderClient(this)
//drawer create and in actions
val drawerLayout: DrawerLayout = findViewById(R.id.draweLayout)
val navWiew: NavigationView = findViewById(R.id.nav_view)
toggle = ActionBarDrawerToggle(this#PricklyMapsActivity, drawerLayout, R.string.open, R.string.close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
navWiew.setNavigationItemSelectedListener {
when (it.itemId){
R.id.Home -> showActivityHome()
R.id.Map -> Toast.makeText(applicationContext, "Alredy at the Map", Toast.LENGTH_SHORT).show()
}
true
}
//drawer create end
//Geofence
geoClient = LocationServices.getGeofencingClient(this)
//add geofences here
val latatude = -26.694340
val longatude = 27.083960
val radius = 10f
geofenceList.add(Geofence.Builder()
.setRequestId("Toets")
.setCircularRegion(latatude,longatude,radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build())
}
override fun onDestroy() {
super.onDestroy()
removeGeofence()
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
getCurrentLocation()
val placeName = arrayOf<String>("Texas")
val lataltude = arrayOf<Double>(-26.694340)
val longatude = arrayOf<Double>(27.083960)
for (i in 0..placeName.size-1){
val x = placeName[i]
val y = lataltude[i]
val z = longatude[i]
addCircle(x, y, z)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(toggle.onOptionsItemSelected(item)){
return true
}
return super.onOptionsItemSelected(item)
}
//go to the home activity
private fun showActivityHome(){
val intent1 = Intent(this#PricklyMapsActivity, MainActivity::class.java)
startActivity(intent1)
}
private fun addCircle(Name: String, latatude: Double, longatude: Double){
val radius = 10.00
val latLng = LatLng(latatude,longatude)
map.addCircle(
CircleOptions()
.radius(radius)
.center(latLng)
.strokeColor(Color.argb(150,173,216,230))
.fillColor(Color.argb(100, 173, 216, 230))
)
}
//Geofence pending intent
private val geofenceIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceBrodcastReceiver::class.java)
intent.action = ACTION_GEOFENCE_EVENT
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
companion object{
internal const val ACTION_GEOFENCE_EVENT =
"PricklyMapsActivity.pricklypear.action.ACTION_GEOFENCE_EVENT"
}
//Specifies the geofence
private fun seekGeofencing(): GeofencingRequest {
return GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofenceList)
}.build()
}
//adds the geofence or geofences
#SuppressLint("MissingPermission")
private fun addGeofence(){
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PERMISSION_GRANTED){
return
}
geoClient?.addGeofences(seekGeofencing(), geofenceIntent)?.run {
addOnSuccessListener {
Toast.makeText(this#PricklyMapsActivity, "Geofence(s) added", Toast.LENGTH_LONG).show()
}
addOnFailureListener {
Toast.makeText(this#PricklyMapsActivity, "Failed to add geofence(s)", Toast.LENGTH_LONG).show()
}
}
}
//Removing geofences
private fun removeGeofence(){
geoClient?.removeGeofences(geofenceIntent)?.run {
addOnSuccessListener {
Toast.makeText(this#PricklyMapsActivity, "Geofences removed", Toast.LENGTH_SHORT).show()
}
addOnFailureListener {
Toast.makeText(this#PricklyMapsActivity, "Failed to remove geofences", Toast.LENGTH_SHORT).show()
}
}
}
//From here and down it is getting location and permition
#SuppressLint("MissingPermission", "NewApi")
private fun getCurrentLocation(){
if (checkPermission()){
if (isLocationEnabled()){
map.isMyLocationEnabled = true
fusedLocatonClient.lastLocation.addOnCompleteListener(this){ task ->
val location: Location?=task.result
if (location==null){
Toast.makeText(this,
"Location may still be turning on pleas wate a while",
Toast.LENGTH_SHORT).show()
}else {
currentLocation = location
myLatlng = LatLng(location.latitude, location.longitude)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatlng, 18f))
addGeofence()
}
Looper.myLooper()
}
}else{
//open settings if location is not enabled
Toast.makeText(this, "Pleas turn on location", Toast.LENGTH_SHORT).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}else{
//requests permition if permition is not granted
requestPermissions()
}
}
//Checker for if the laocation is enabled return boolean
private fun isLocationEnabled(): Boolean{
val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
//Checker for if the location permission is enabled return boolean
#TargetApi(29)
private fun checkPermission(): Boolean{
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PERMISSION_GRANTED){
if (gadgetQ){
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
PERMISSION_GRANTED) {
return true
}
}else {
return true
}
}
return false
}
private fun requestPermissions(){
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION), permissionId
//android.Manifest.permission.ACCESS_BACKGROUND_LOCATION), permissionId
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == permissionId){
if (grantResults.isNotEmpty() && grantResults[0] == PERMISSION_GRANTED){
getCurrentLocation()
}else{
Toast.makeText(this, "location is not granted", Toast.LENGTH_SHORT).show()
}
}
}
}
Brodcast receiver Class
class GeofenceBrodcastReceiver: BroadcastReceiver() {
private lateinit var database: DatabaseReference
override fun onReceive(context: Context?, intent: Intent?) {
val geofencingEvent = GeofencingEvent.fromIntent(intent!!)
val geofencingTransition = geofencingEvent!!.geofenceTransition
if (geofencingTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
database = FirebaseDatabase.getInstance().getReference("Texas")
database.child("Count").get().addOnSuccessListener {
if (it.exists()) {
var number = it.getValue(Long::class.java)
if (number is Long){
number += 1
val post =mapOf<String, Long>("Count" to number)
database.updateChildren(post)
}
} else {
Log.e(TAG, "Invalid type transition")
}
}.addOnFailureListener {
Log.e(TAG, "Invalid type transition")
}
}
}
}
At the pending intent I tried changing the type, but it did not work. I have looked every ware and as far as I can tell there is no problem with my code, and it should work so if someone can help me it would be much appreciated.

NullPointerException when using Kotlin Synthetic

I am getting a NullPointerException when I try to access an element in the layout from a DialogFragment. I have checked that, if I call getView() inside the same DialogFragment the result is 'null'.
Thank you in advance!
This is the Activity that calls commits the FragmentDialog "NewPOIDialog"
class MainActivity : AppCompatActivity() {
//Variables for Location service
private var hasGps: Boolean = false
private var hasNetwork: Boolean = false
private var locationGps: Location? = null
private var locationNetwork: Location? = null
private companion object {
private const val TAG = "MainActivity"
}
private lateinit var auth: FirebaseAuth
private lateinit var permissionsRequestor: PermissionsRequestor
private lateinit var mapView: MapView
private lateinit var mapActivity: MapActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
//Get the authorisation from Firebase
auth = Firebase.auth
Log.d("", "HERE SDK version: " + SDKBuildInformation.sdkVersion().versionName)
// Get a MapView instance from layout.
mapView = findViewById(R.id.map_view)
mapView.onCreate(savedInstanceState)
location()
handleAndroidPermissions()
}
fun searchInMap(view: View?) {
NewPOIDialog().show(supportFragmentManager, "test")
}
fun clearRouteButtonClicked(view: View?) {
mapActivity.clearMap()
}
fun clearWaypoints(view: View?) {
mapActivity.clearWaypoints()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true //we provided the menu that needs to be inflated
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.miLogout) {
Log.i(TAG, "Logout")
//Logout the user
auth.signOut()
LoginManager.getInstance().logOut()
val logoutIntent = Intent(this, LoginActivity::class.java)
logoutIntent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK //Clear the backstack
startActivity(logoutIntent)
}
return super.onOptionsItemSelected(item)
}
private fun handleAndroidPermissions() {
permissionsRequestor = PermissionsRequestor(this)
permissionsRequestor.request(object : PermissionsRequestor.ResultListener {
override fun permissionsGranted() {
loadMapScene()
}
override fun permissionsDenied() {
Log.e(TAG, "Permissions denied by user.")
}
})
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
permissionsRequestor.onRequestPermissionsResult(requestCode, grantResults)
}
private fun loadMapScene() {
mapView.mapScene.loadScene(MapScheme.NORMAL_DAY, object : MapScene.LoadSceneCallback {
override fun onLoadScene(p0: MapError?) {
if (p0 == null) {
mapActivity = MapActivity(this#MainActivity, mapView, supportFragmentManager)
mapView.camera.lookAt(
GeoCoordinates(53.57407651646072, -1.525012498490556),
100000.0
)
} else {
Log.d("TAG", "onLoadScene failed: $p0")
}
}
})
}
fun location() {
var locationManager: LocationManager = getSystemService(LOCATION_SERVICE) as LocationManager
hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
if (hasGps || hasNetwork) {
if (hasGps) {
Log.d(TAG, "hasGPS")
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return
handleAndroidPermissions()
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0f,
object :
LocationListener {
override fun onLocationChanged(p0: Location?) {
if (p0 != null) {
locationNetwork = p0
}
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
}
override fun onProviderEnabled(p0: String?) {
}
override fun onProviderDisabled(p0: String?) {
}
})
val localGpsLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (localGpsLocation != null) {
locationGps = localGpsLocation
}
}
///////////////////////////////////////////////////////////////////////////
if (hasNetwork) {
Log.d(TAG, "hasGPS")
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0f,
object :
LocationListener {
override fun onLocationChanged(p0: Location?) {
if (p0 != null) {
locationNetwork = p0
}
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
}
override fun onProviderEnabled(p0: String?) {
}
override fun onProviderDisabled(p0: String?) {
}
})
val localGpsLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (localGpsLocation != null) {
locationGps = localGpsLocation
}
val localNetworkLocation =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (localNetworkLocation != null) {
locationNetwork = localNetworkLocation
}
if (locationGps != null && locationNetwork != null) {
if (locationGps!!.accuracy!! > locationNetwork!!.accuracy!!) { //The lower number is the accurate location
Log.d(TAG, "Network Latitude : ${locationNetwork!!.latitude}")
Log.d(TAG, "Network Longitude : ${locationNetwork!!.longitude}")
latitude_txt.text = "Latitude : ${locationNetwork!!.latitude} - Network"
longitude_txt.text = "Longitude : ${locationNetwork!!.longitude} - Network"
latitude_txt.text = "Latitude : ${locationGps!!.latitude} - Gps"
longitude_txt.text = "Longitude : ${locationGps!!.longitude} - Gps"
} else {
Log.d(TAG, "Gps Latitude : ${locationGps!!.latitude}")
Log.d(TAG, "Gps Longitude : ${locationGps!!.longitude}")
latitude_txt.text = "Latitude : ${locationGps!!.latitude} - Gps"
longitude_txt.text = "Longitude : ${locationGps!!.longitude} - Gps"
}
}
}
// if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
// this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)
// ) {
// locationManager.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
// LOCATION_UPDATE_INTERVAL_IN_MS,
// 1,
// this
// );
// } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// locationManager.requestLocationUpdates(
// LocationManager.NETWORK_PROVIDER,
// LOCATION_UPDATE_INTERVAL_IN_MS,
// 1,
// this
// );
// } else {
// Log.d(TAG, "Positioning not possible.");
// // ...
// }
}
}
}
NewPOIDialog
The view was initially called as below, I changed it as I was receiving a StackOverFlowError:
var view = layoutInflater.inflate(R.layout.activity_new_poi_dialog,null)
class NewPOIDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
var view = LayoutInflater.from(context).inflate(R.layout.activity_new_poi_dialog, null)
var dialog = AlertDialog.Builder(requireContext())
.setMessage("TITLE")
.setView(view)
.setPositiveButton("ok") { _, _ -> }
.setNegativeButton("Cancel") { _, _ -> }
.create()
//THIS LINE WORKS FINE
var coordinatesvalue = view.findViewById<TextView>(R.id.coordinates_value)
coordinatesvalue.text =
"${arguments?.getDouble("latitude")}\n, ${arguments?.getDouble("longitude")}"
//THIS CAUSES A NULL POINTER EXCEPTION
coordinates_value.text = "TEST"
return dialog
}
}
The exception I am getting:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robin.socialparking, PID: 19187
java.lang.NullPointerException: coordinates_value must not be null
at com.robin.socialparking.dialog.NewPOIDialog.onCreateDialog(NewPOIDialog.kt:54)
at androidx.fragment.app.DialogFragment.onGetLayoutInflater(DialogFragment.java:380)
at androidx.fragment.app.Fragment.performGetLayoutInflater(Fragment.java:1412)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I/Process: Sending signal. PID: 19187 SIG: 9

lateinit property mapRoute has not been initialized

I'm trying to make an app where it tracks the user and draws out the route the user has taken.
Whenever I try to install the app on the AVD the app keeps crashing and I get the error message that lateinit has not been initialized.
This is my code:
package com.example.map2020
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var map: GoogleMap
private lateinit var mapRoute: PolylineOptions
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var mCurrentLocation: Location
private lateinit var locationRequestTask: Task<LocationSettingsResponse>
private lateinit var locationCallback: LocationCallback
private lateinit var locationRequest: LocationRequest
private var requestingLocationUpdates = true
private val REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
private val TAG = MapsActivity::class.java.simpleName
private val REQUEST_LOCATION_PERMISSION = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
mapFragment?.getMapAsync(this)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
locationRequest = LocationRequest.create()?.apply({
interval = 5000
fastestInterval = 3000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
})!!
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
if (location != null) {
mCurrentLocation = location
}
}
locationRequestTask = createLocationRequest()
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations){
mapRoute.add(LatLng(location.latitude, location.longitude))
map.addPolyline(mapRoute)
}
}
}
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
val zoomLevel = 15f
val homeLatLng = LatLng(-6.240423, 106.605836)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel))
map.addMarker(MarkerOptions().position(homeLatLng))
mapRoute = PolylineOptions()
.width(8f)
.color(Color.GREEN)
map.addPolyline(mapRoute)
enableMyLocation()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.map_options, menu)
return true
}
// Checks that users have given permission
private fun isPermissionGranted() : Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
// Checks if users have given their location and sets location enabled if so.
private fun enableMyLocation() {
if (isPermissionGranted()) {
map.isMyLocationEnabled = true
}
else {
ActivityCompat.requestPermissions(
this,
arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}
}
// Callback for the result from requesting permissions.
// This method is invoked for every call on requestPermissions(android.app.Activity, String[],
// int).
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
// Check if location permissions are granted and if so enable the
// location data layer.
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
enableMyLocation()
}
}
}
fun createLocationRequest(): Task<LocationSettingsResponse> {
val builder = locationRequest.let {
LocationSettingsRequest.Builder()
.addLocationRequest(it)
}
val client: SettingsClient = LocationServices.getSettingsClient(this)
return client.checkLocationSettings(builder.build())
}
override fun onResume() {
super.onResume()
if (requestingLocationUpdates) startLocationUpdates()
}
private fun startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper())
}
override fun onPause() {
super.onPause()
stopLocationUpdates()
}
private fun stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback)
}}
This is my error code:
kotlin.UninitializedPropertyAccessException: lateinit property mapRoute has not been initialized
at com.example.map2020.MapsActivity.access$getMapRoute$p(MapsActivity.kt:31)
at com.example.map2020.MapsActivity$onCreate$3.onLocationResult(MapsActivity.kt:73)
at com.google.android.gms.internal.location.zzau.notifyListener(Unknown Source)
at com.google.android.gms.common.api.internal.ListenerHolder.notifyListenerInternal(Unknown Source)
at com.google.android.gms.common.api.internal.ListenerHolder$zaa.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at com.google.android.gms.internal.base.zap.dispatchMessage(Unknown Source)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Because callback locationCallback called before onMapReady. I recommend you startLocationUpdates() in onMapReady too. In onResume should check isMapReady too. You need flag to store map visible completely inside onMapReady

App crashes right after asking for location permission for the first time in frament

I am working in Kotlin and my fragment lies inside an activity. So when I run my app and as soon as the location fragment opens up it asks me for the permission but immediately crashes, so I'm unable to allow or deny the permission.
Here's my code for location fragment:
package com.example.atry.MakeComplaint
import android.app.Activity
import android.app.Activity.RESULT_OK
import com.example.atry.Retrofit.INodeJS
import com.example.atry.Retrofit.Observables
import com.example.atry.Retrofit.RetrofitClient
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.*
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Switch
import android.widget.Toast
import com.google.android.gms.maps.MapView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.atry.R
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.*
import kotlinx.android.synthetic.main.fragment_location.view.*
import retrofit2.Call
import retrofit2.Response
class LocationFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
override fun onMarkerClick(p0: Marker?)= false
private lateinit var map: GoogleMap
private lateinit var mapView : MapView
private lateinit var restrict:LatLngBounds
lateinit var myAPI: INodeJS
var MyCategory: Observables.Complainttype?=null
private var listener: OnLocationFragmentInteractionListener? = null
var makeComplaintobject1:Observables.final?=null
lateinit var typename:String
var objectComplaint =
Observables.Complaint(
1 , "dummy problem" ,
"url" ,
Observables.Location("78.4","17.4"),
Observables.ComplaintTypes("Smell" ),
Observables.Status( "Unresolved")
)
//for updating user's location/ for current location
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
// private lateinit var lastLocation: Location
var lastLocation:Location?=null
private var locationUpdateState = false
companion object {
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
private const val REQUEST_CHECK_SETTINGS = 2 //For updating user's location as they move
}
fun sendCategoryItem(category: Observables.Complainttype) {
//receiving the category selected from Category Fragment
this.MyCategory = category
Log.d("here", "i am here 1")
Log.d("here", MyCategory.toString())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
if (locationResult.locations.isNotEmpty()) {
// get latest location and sets it on the map
lastLocation = locationResult.lastLocation
Log.d("lastlocation", lastLocation.toString())
placeMarkerOnMap(LatLng(lastLocation!!.latitude, lastLocation!!.longitude))
} } }
getLocationUpdates()
//INIT API
val retrofit = RetrofitClient.instanc
myAPI = retrofit.create(INodeJS::class.java)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_location, container, false)
mapView = v.findViewById(R.id.maps)
mapView.onCreate(savedInstanceState)
mapView.onResume()
try {
MapsInitializer.initialize(getActivity()!!.getApplicationContext())
} catch (sendEx: IntentSender.SendIntentException) {
sendEx.printStackTrace()
}
mapView.getMapAsync(this)
v.backToList.setOnClickListener {
backFragment()
}
v.forwardToDescription.setOnClickListener{
//will proceed to the Category Description fragment only if the lastLocation isn't null
getAllData()
}
return v
}
private fun setUpMap() {
if (activity!!.checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
return
}
}
private fun checkForPermissions(){
if(activity!!.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions( arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
}
startLocationUpdates()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(grantResults.size >0){
if(requestCode== LOCATION_PERMISSION_REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED){
locationUpdateState=true
checkForPermissions()
}
}
}
/**
* call this method in onCreate
* onLocationResult call when location is changed
*/
private fun getLocationUpdates() {
//with fusedLocationClient
// fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
locationRequest = LocationRequest()
locationRequest.interval = 1000
locationRequest.fastestInterval = 5000
locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val client = LocationServices.getSettingsClient(context!!)
val task = client.checkLocationSettings(builder.build())
//can update the map if location services on
task.addOnSuccessListener {
locationUpdateState=true
checkForPermissions()
}
task.addOnFailureListener { e ->
//check if the location settings is on yet
if(e is ResolvableApiException){
try{
e.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS)
}catch (sendEx : IntentSender.SendIntentException){
}
}
}
}
//Places the marker on the map and changes its style.
private fun placeMarkerOnMap(location: LatLng) {
// 1
val markerOptions = MarkerOptions().position(location)
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
// 2
map.addMarker(markerOptions)
}
//start location updates
private fun startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
null /* Looper */
)
}
// stop location updates
private fun stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback)
}
// start receiving location update when activity visible/foreground
override fun onResume() {
super.onResume()
mapView.onResume()
checkForPermissions()
// startLocationUpdates()
}
// stop receiving location update when activity not visible/foreground
override fun onPause() {
super.onPause()
mapView.onPause()
stopLocationUpdates()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override public fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onMapReady(googleMap: GoogleMap?) {
map = googleMap!!
map.uiSettings?.isZoomControlsEnabled = true
setUpMap()
map.isMyLocationEnabled = true
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
//updating the map with user's current location
if (location !=null){
lastLocation = location
val currentLatLng = LatLng(location.latitude,location.longitude)
placeMarkerOnMap(currentLatLng)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,12f))
}
}
}
private fun backFragment() {
val manager = (context as AppCompatActivity).supportFragmentManager
manager.popBackStackImmediate()
}
fun getAllData(){
//
// val latitude = 17.4
// val longitude = 78.4
// LocationUtils().getInstance(appContext)
// LocationUtils().getLocation().observe(this, Observer {loc: Location? ->
// location = loc!!
// // Yay! location recived. Do location related work here
// Log.i(TAG,"Location: ${location.latitude} ${location.longitude}")
//
// })
if(lastLocation!=null){
makeComplaintobject1 = Observables.final(
Observables.ComplaintTypes(MyCategory!!.typeName),
// Observables.Location(lastLocation.longitude.toString(),lastLocation.latitude.toString()) //lateinit wala
Observables.Location(lastLocation!!.longitude.toString(),lastLocation!!.latitude.toString())
)
}
else{
makeComplaintobject1 = Observables.final(
Observables.ComplaintTypes(MyCategory!!.typeName),
// Observables.Location(lastLocation.longitude.toString(),lastLocation.latitude.toString()) //lateinit wala
Observables.Location("","")
)
}
typename = MyCategory!!.typeName
val call = myAPI.checkExistingComplain(typename,makeComplaintobject1!!.finalLocation.longitude, makeComplaintobject1!!.finalLocation.latitude ) //new
Log.d("T", typename)
Log.d("Lo", makeComplaintobject1!!.finalLocation.longitude)
Log.d("La", makeComplaintobject1!!.finalLocation.latitude)
call.enqueue(object : retrofit2.Callback<Observables.checkExistingResult> {
override fun onFailure(call: Call<Observables.checkExistingResult>?, t: Throwable?) {
Log.d("NO", t!!.message)
}
override fun onResponse(call: Call<Observables.checkExistingResult>?, response: Response<Observables.checkExistingResult>?) {
Log.d("response popup", response!!.code().toString())
//
if(response.code() == 200){
Log.d("YES", response.code().toString())
Log.d("response", response.body().toString())
if(response.body()!!.Complain === null){
//if type and location are in db but does not match
Log.d("null",response.body()!!.Complain.toString())
var item1 = makeComplaintobject1
Log.d("wohoooooo",makeComplaintobject1.toString())
listener!!.onLocationFragmentInteraction1(item1!!) // typeName and location going to category description
}
else{
//if location or type matched
objectComplaint = response.body()!!.Complain!!
Log.d("got the complaint",objectComplaint.toString())
setExistingData(objectComplaint)
val item = objectComplaint
listener!!.onLocationFragmentInteraction(item) // all complaint going to popup
}
}
else if(response.code() == 500){
//if location or type is not in db
Log.d("response error", response.body().toString())
var item1 = makeComplaintobject1
Log.d("NOT IN DB",makeComplaintobject1.toString())
listener!!.onLocationFragmentInteraction1(item1!!) // typeName and location going to category description
}
else{
var item1 = makeComplaintobject1
Log.d("wohoooooo!1111",makeComplaintobject1.toString())
listener!!.onLocationFragmentInteraction1(item1!!) // typeName and location going to category description
//descriptionFragment()
}
}
})
}
interface OnLocationFragmentInteractionListener {
fun onLocationFragmentInteraction(item: Observables.Complaint?) // all complaint going to popup
fun onLocationFragmentInteraction1(item1: Observables.final) // typeName and location going to category description
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnLocationFragmentInteractionListener) {
listener = context
}
else {
throw RuntimeException("$context must implement OnLocationFragmentInteractionListener")
}
}
fun setExistingData(test: Observables.Complaint) {
objectComplaint = test
}
}
I have already asked for the ACCESS_FINE_LOCATION permission in the manifest and my min sdk version is 23 while targetsdk is 26.
After a lot of tries I am still getting the following error.
java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
What can I do to resolve this error?
If you are running on Marshmallow or greater version then you need to check permission of ACCESS_FINE_LOCATION if user has granted or not if not then you will get SecurityException when you try to access location without user consent. so before accessing location You check like this -
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// you can access LOCATION
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 411);
}
}
else
{
// you can access LOCATION
}
Get Result of the Permission dialog,
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 411) {
if (grantResults.length == 0 || grantResults == null) {
// show dialog that you need access to go ahead
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Your code here permission granted
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// show dialog that you need access to go ahead
}
}
}
Now coming to your code
private fun checkForPermissions(){
if(activity!!.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions( arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
}
startLocationUpdates()
}
Right after
if(activity!!.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
this if condition end you are calling
startLocationUpdates()
so that's why after permission dialog system call this method and try to get location updates without user consent and app crash with SecurityException.
Your updates method could like below -
private fun checkForPermissions(){
if(activity!!.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions( arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
}else{
startLocationUpdates()
}
}
Hope this will help you.

Why location is allways null in this case?

can anyone tell me why when I call the function initPetrolStationList() in first if condition currentLocation is allways null but when I call te function addPetrolStation(v: View) is initilized? I would like that when the function initPetrolStationList()is called currentLocation will be not null.
class PetrolStationListActivity : AppCompatActivity() {
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private lateinit var listView: RecyclerView
private var currentLocation: Location? = null
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//some code
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.petrol_station_list_view)
requestLocationPermission()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
getLastLocation()
initPetrolStationList()
}
fun addPetrolStation(v: View) {
if (currentLocation != null) {
val googleMapController = GoogleMapsController()
googleMapController.getPetrolStationFromGoogle(object : GoogleResponse {
override fun getLocation(): Location = currentLocation!!
override fun getResponse(body: GoogleMapResponse) {
if (body.status == "OK") {
val intent = Intent(applicationContext, PetrolStationActivity::class.java)
v.context.startActivity(intent)
} else {
Toast.makeText(applicationContext, "Petrol station not found", Toast.LENGTH_LONG).show()
}
}
})
}
}
#SuppressLint("MissingPermission")
private fun getLastLocation() {
fusedLocationProviderClient.lastLocation.addOnCompleteListener {
if (it.isSuccessful) {
currentLocation = it.result!!
Log.d("Current location: ", "Lat:${currentLocation!!.latitude}, Lng:${currentLocation!!.longitude}")
} else {
Log.d("Location exception: ", it.exception?.message)
Toast.makeText(this, "Location not found :( ", Toast.LENGTH_LONG).show()
}
}
}
private fun initPetrolStationList() {
if (currentLocation != null) {
val petrolStationController = PetrolStationController()
//some code
} else Toast.makeText(this, "Location not found", Toast.LENGTH_LONG).show()
}
}
If you call initPetrolStationList from inside getLastLocation after currentLocation = it.result!! then currentLocation will not be null.
Try to initialize petrolStationController immediately
Add fusedLocationProviderClient.lastLocation.addOnCompleteListener in onCreate
And update data of petrolStationController in this listener

Categories

Resources