android - lateinit 属性 mapRoute 尚未初始化
问题描述
我正在尝试制作一个应用程序来跟踪用户并绘制出用户所走的路线。每当我尝试在 AVD 上安装该应用程序时,该应用程序都会崩溃,并且我会收到错误消息,指出 Lateinit 尚未初始化。
这是我的代码:
package com.example.map2020
类 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)
}}
这是我的错误代码:
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)
解决方案
因为回调 locationCallback 在 onMapReady 之前调用。我也建议您在 onMapReady 中使用 startLocationUpdates()。在 onResume 中也应该检查 isMapReady。您需要标志来存储地图完全可见 onMapReady
推荐阅读
- python - Python链表-递归删除函数中的Nonetype错误
- mysql - 如何使用 Azure 上的 VM 和我的 PC 上的 VM 连接主副本和从副本?
- c - 如何用 C 编写一个程序,从 linux 命令的结果中打印一些列?
- node.js - 带有嵌入对象的nestjs mongoose模式,没有嵌入文档
- javascript - 在 Safari 网络检查器中,是否可以在除指定事件之外的所有事件上停止?
- c# - 如何从不同的脚本更改此值?统一 C#
- reactjs - React Router:单击映射项目到新页面
- python - SQLAlchemy 1.4 ORM 中 Query.count 的等价物是什么?
- voice - 如何进行语音再合成以将女性声音转换为男性声音
- iis - localhost 解析为旧计算机名