我正在尝试添加从当前位置到目的地的路线。我已经完成了代码并遵循了相应的教程,但该应用一次又一次崩溃。我不明白怎么了。我在这里分享我的代码。问题尚未解决,并且lagcat无法共享此处已满的身体限制。
class ViewDirections : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mService : GoogleService
private lateinit var mMap: GoogleMap
var polyline: Polyline? = null
lateinit var mCurrentMarker : Marker
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
lateinit var mLastLocation : Location
//private var permissions : Array<String> = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION)
companion object {
private const val PERMISSION_REQUEST: Int = 10
}
private fun buildLocationRequest() {
locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 5000
locationRequest.fastestInterval = 3000
locationRequest.smallestDisplacement = 10f
}
private fun buildLocationCallback() {
locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
//Get Last location
mLastLocation = p0!!.lastLocation
val markerOptions = MarkerOptions()
.position(LatLng(mLastLocation.latitude,mLastLocation.longitude))
.title("My Position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mCurrentMarker = mMap.addMarker(markerOptions)
mMap.moveCamera(CameraUpdateFactory.newLatLng(LatLng(mLastLocation.latitude,mLastLocation.longitude)))
mMap.animateCamera(CameraUpdateFactory.zoomTo(11f))
val destinationLatLng = LatLng(Common.currentResults!!.geometry!!.location!!.lat,
Common.currentResults!!.geometry!!.location!!.lng)
mMap.addMarker(MarkerOptions().position(destinationLatLng)
.title(Common.currentResults!!.name))
.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
//Get Direction
drawPath(mLastLocation,Common.currentResults!!.geometry!!.location!!)
}
}
}
private fun drawPath(mLastLocation: Location?, location : com.malik.testapplication.Model.Location) {
if (polyline!= null)
polyline!!.remove()
val origin = StringBuilder(mLastLocation!!.latitude.toString())
.append(",")
.append(mLastLocation.longitude.toString())
.toString()
val destination = StringBuilder(location.lat.toString())
.append(",")
.append(location.lng.toString())
.toString()
mService.getDirections(origin,destination)
.enqueue(object : Callback<String>{
override fun onFailure(call: Call<String>, t: Throwable) {
Log.d("Kotlin",t.message)
}
override fun onResponse(call: Call<String>, response: Response<String>) {
ParserTask().execute(response.body()!!.toString())
} })
}
override fun onStop() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
super.onStop() }
private fun checkLocationPermission(): Boolean {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
ViewDirections.PERMISSION_REQUEST
)
else
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
ViewDirections.PERMISSION_REQUEST
)
return false
} else
return true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_directions)
// 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)
mService = Common.googleApiScalarService
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkLocationPermission()) {
buildLocationRequest()
buildLocationCallback()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.myLooper()
)
} else {
buildLocationRequest()
buildLocationCallback()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.myLooper()
)
}
}
}
//@RequiresApi(Build.VERSION_CODES.M)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
ViewDirections.PERMISSION_REQUEST -> {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Toast.makeText(this, "Location is ON", Toast.LENGTH_SHORT).show()
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
)
if (checkLocationPermission()) {
buildLocationRequest()
buildLocationCallback()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.myLooper()
)
mMap.isMyLocationEnabled = true
}
} else {
Toast.makeText(this, "Permission is denied", Toast.LENGTH_SHORT).show()
}
}
}
}
@SuppressLint("MissingPermission")
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.uiSettings.isZoomControlsEnabled = true
fusedLocationProviderClient.lastLocation.addOnSuccessListener { location ->
mLastLocation = location
val markerOptions = MarkerOptions()
.position(LatLng(mLastLocation.latitude,mLastLocation.longitude))
.title("My Position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mCurrentMarker = mMap.addMarker(markerOptions)
mMap.moveCamera(CameraUpdateFactory.newLatLng(LatLng(mLastLocation.latitude,mLastLocation.longitude)))
mMap.animateCamera(CameraUpdateFactory.zoomTo(11f))
val destinationLatLng = LatLng(Common.currentResults!!.geometry!!.location!!.lat,
Common.currentResults!!.geometry!!.location!!.lng)
mMap.addMarker(MarkerOptions().position(destinationLatLng)
.title(Common.currentResults!!.name))
.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
//Get Direction
drawPath(mLastLocation,Common.currentResults!!.geometry!!.location!!)
}
}
inner class ParserTask : AsyncTask<String,Int,List<List<HashMap<String,String>>>>() {
internal val waitingDialog : AlertDialog = SpotsDialog(this@ViewDirections)
override fun onPreExecute() {
super.onPreExecute()
waitingDialog.show()
waitingDialog.setMessage("Please Wait...")
}
override fun doInBackground(vararg params: String?): List<List<HashMap<String, String>>>? {
val jsonObject : JSONObject
var routes : List<List<HashMap<String, String>>>? =null
try {
jsonObject = JSONObject(params[0])
val parser = DirectionJSONParser()
routes = parser.parse(jsonObject)
}catch (e : JSONException){
e.printStackTrace()
}
return routes
}
override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
super.onPostExecute(result)
var points : ArrayList<LatLng>
var polylineOptions : PolylineOptions? = null
for(i in result!!.indices){
points = ArrayList()
polylineOptions = PolylineOptions()
val path =result[i]
for (j in path.indices){
val point = path[j]
val lat = point["lat"]!!.toDouble()
val lng = point["lng"]!!.toDouble()
val position = LatLng(lat,lng)
points.add(position)
}
polylineOptions.addAll(points)
polylineOptions.width(12f)
polylineOptions.color(Color.RED)
polylineOptions.geodesic(true)
}
polyline = mMap.addPolyline(polylineOptions)
waitingDialog.dismiss()
}
}
}
Logcat:
2018-11-16 15:04:40.817 4720-16409/? E/ActivityManager: getPackageFromAppProcesses, return null :22519
2018-11-16 15:04:40.861 22522-22522/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2018-11-16 15:04:40.873 2602-3503/? E/audio_hw_primary: adev_close_input_stream, set jack_in to null
2018-11-16 15:04:40.902 22506-22506/? E/appproc: Enhanced Zygote ASLR: ro.knox.enhance.zygote.aslr != 1. Enhanced Zygote ASLR is DISABLED!
2018-11-16 15:04:40.923 18326-18326/? E/adbd: recv: OPEN 0000001e 00000000 000b:6A 64 77 70 3A 32 32 35 32 32 00
2018-11-16 15:04:41.153 22506-22506/? E/SemAffinityControl: SemAffinityControl: registerfunction enter
2018-11-16 15:04:41.430 4720-4804/? E/WindowManager: win=Window{856ed4e u0 com.sec.android.app.launcher/com.sec.android.app.launcher.activities.LauncherActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8, caller=com.android.server.wm.AppWindowToken.destroySurfaces:748 com.android.server.wm.AppWindowToken.destroySurfaces:732 com.android.server.wm.WindowState.onExitAnimationDone:5523 com.android.server.wm.AppWindowAnimator.stepAnimationLocked:517 com.android.server.wm.AppWindowToken.stepAppWindowsAnimation:1745
2018-11-16 15:04:42.026 5354-5397/? E/RequestManager_FLP: [LocationManagerService] Location request bdc04d3 gps interval=5000 from com.google.android.gms.persistent
2018-11-16 15:04:42.027 4720-5491/? E/PermissionMonitor: (NameNotFoundException) ApplicationInfo for (com.google.uid.shared) is null! UserId: 0
2018-11-16 15:04:42.066 5354-5397/? E/RequestManager_FLP: [LocationManagerService] Location request bdc04d3 gps interval=5000 from com.google.android.gms.persistent
2018-11-16 15:04:42.394 4720-4804/? E/WindowManager: win=Window{40cef14 u0 Splash Screen com.malik.testapplication EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0, caller=com.android.server.wm.AppWindowToken.destroySurfaces:748 com.android.server.wm.AppWindowToken.destroySurfaces:732 com.android.server.wm.WindowState.onExitAnimationDone:5523 com.android.server.wm.WindowStateAnimator.stepAnimationLocked:553 com.android.server.wm.DisplayContent.lambda$-com_android_server_wm_DisplayContent_21292:465
2018-11-16 15:04:52.130 4720-4804/? E/WindowManager: win=Window{23c455b u0 com.malik.testapplication/com.malik.testapplication.MapsActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8, caller=com.android.server.wm.AppWindowToken.destroySurfaces:748 com.android.server.wm.AppWindowToken.destroySurfaces:732 com.android.server.wm.WindowState.onExitAnimationDone:5523 com.android.server.wm.WindowStateAnimator.stepAnimationLocked:553 com.android.server.wm.DisplayContent.lambda$-com_android_server_wm_DisplayContent_21292:465
2018-11-16 15:04:52.176 5354-5397/? E/RequestManager_FLP: [LocationManagerService] Location remove bdc04d3 from com.google.android.gms.persistent
2018-11-16 15:04:53.157 5354-5397/? E/RequestManager_FLP: [LocationManagerService] Location request d21d6b8 gps interval=5000 from com.google.android.gms.persistent
2018-11-16 15:04:53.160 4720-5801/? E/PermissionMonitor: (NameNotFoundException) ApplicationInfo for (com.google.uid.shared) is null! UserId: 0
2018-11-16 15:04:53.708 4720-4804/? E/WindowManager: win=Window{72d604 u0 com.malik.testapplication/com.malik.testapplication.ViewPlaces EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8, caller=com.android.server.wm.AppWindowToken.destroySurfaces:748 com.android.server.wm.AppWindowToken.destroySurfaces:732 com.android.server.wm.WindowState.onExitAnimationDone:5523 com.android.server.wm.AppWindowAnimator.stepAnimationLocked:517 com.android.server.wm.AppWindowToken.stepAppWindowsAnimation:1745
2018-11-16 15:04:54.033 22522-22522/com.malik.testapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.malik.testapplication, PID: 22522
kotlin.KotlinNullPointerException
at com.malik.testapplication.ViewDirections$drawPath$1.onResponse(ViewDirections.kt:117)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
2018-11-16 15:04:54.823 4720-5167/? E/LightsService: Light requested not available on this device. 2
2018-11-16 15:04:55.320 4720-4730/? E/KioskModeService: There's no matched data
2018-11-16 15:04:55.341 4720-4730/? E/KioskModeService: There's no matched data
2018-11-16 15:04:55.363 4720-4730/? E/KioskModeService: There's no matched data
2018-11-16 15:04:55.384 4720-4730/? E/ActivityManager: Found activity ActivityRecord{465da4e u0 com.malik.testapplication/.MapsActivity t-1 f} in proc activity list using null instead of expected ProcessRecord{414662d 22522:com.malik.testapplication/u0a246}
2018-11-16 15:04:55.417 4720-4736/? E/ViewRootImpl: sendUserActionEvent() returned.
2018-11-16 15:04:55.439 12234-12234/? E/PBSessionCacheImpl: sessionId[53807243290634637] not persisted.
2018-11-16 15:04:55.478 5354-5397/? E/RequestManager_FLP: [LocationManagerService] Location remove d21d6b8 from com.google.android.gms.persistent
2018-11-16 15:04:55.676 32306-20762/? E/XXX: Going to delete [com.google.android.gms.lockbox, , 1]
2018-11-16 15:04:55.679 32306-20762/? E/XXX: Going to delete [com.google.android.gms.lockbox, tayb125.ta@gmail.com, 1]
2018-11-16 15:04:55.680 32306-20762/? E/XXX: Going to delete [com.google.android.gms.easysignin, , 1]
2018-11-16 15:04:55.681 32306-20762/? E/XXX: Going to delete [com.google.android.gms.easysignin, tayb125.ta@gmail.com, 1]
2018-11-16 15:04:55.682 32306-20762/? E/XXX: Going to delete [com.google.android.gms.netrec, , 216]
2018-11-16 15:04:55.685 32306-20762/? E/XXX: Going to delete [com.google.android.gms.netrec, tayb125.ta@gmail.com, 216]
2018-11-16 15:04:55.687 32306-20762/? E/XXX: Going to delete [com.google.android.gms.subscriptions, , 205]
2018-11-16 15:04:55.688 32306-20762/? E/XXX: Going to delete [com.google.android.gms.subscriptions, tayb125.ta@gmail.com, 205]
2018-11-16 15:04:55.689 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_api_phone, , 208]
2018-11-16 15:04:55.690 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_api_phone, tayb125.ta@gmail.com, 208]
2018-11-16 15:04:55.691 32306-20762/? E/XXX: Going to delete [com.google.android.gms.beacon, , 232]
2018-11-16 15:04:55.692 32306-20762/? E/XXX: Going to delete [com.google.android.gms.beacon, tayb125.ta@gmail.com, 232]
2018-11-16 15:04:55.693 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustlet_place, , 205]
2018-11-16 15:04:55.694 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustlet_place, tayb125.ta@gmail.com, 205]
2018-11-16 15:04:55.695 32306-20762/? E/XXX: Going to delete [com.google.android.gms.locationsharing.config, , 210]
2018-11-16 15:04:55.696 32306-20762/? E/XXX: Going to delete [com.google.android.gms.locationsharing.config, tayb125.ta@gmail.com, 210]
2018-11-16 15:04:55.697 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_folsom, , 2]
2018-11-16 15:04:55.700 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_folsom, tayb125.ta@gmail.com, 2]
2018-11-16 15:04:55.701 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustagent, , 212]
2018-11-16 15:04:55.702 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustagent, tayb125.ta@gmail.com, 212]
2018-11-16 15:04:55.703 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustlet_onbody, , 203]
2018-11-16 15:04:55.704 32306-20762/? E/XXX: Going to delete [com.google.android.gms.trustlet_onbody, tayb125.ta@gmail.com, 203]
2018-11-16 15:04:55.705 32306-20762/? E/XXX: Going to delete [com.google.android.gms.languageprofile, , 201]
2018-11-16 15:04:55.706 32306-20762/? E/XXX: Going to delete [com.google.android.gms.languageprofile, tayb125.ta@gmail.com, 201]
2018-11-16 15:04:55.707 32306-20762/? E/XXX: Going to delete [com.google.android.gms.gconnect, , 1]
2018-11-16 15:04:55.710 32306-20762/? E/XXX: Going to delete [com.google.android.gms.gconnect, tayb125.ta@gmail.com, 1]
2018-11-16 15:04:55.712 32306-20762/? E/XXX: Going to delete [com.google.android.gms.car_setup, , 210]
2018-11-16 15:04:55.713 32306-20762/? E/XXX: Going to delete [com.google.android.gms.car_setup, tayb125.ta@gmail.com, 210]
2018-11-16 15:04:55.714 32306-20762/? E/XXX: Going to delete [com.google.android.gms.devicedoctor, , 208]
2018-11-16 15:04:55.715 32306-20762/? E/XXX: Going to delete [com.google.android.gms.devicedoctor, tayb125.ta@gmail.com, 208]
2018-11-16 15:04:55.716 32306-20762/? E/XXX: Going to delete [alt.com.google.android.gms.devicedoctor, , 208]
2018-11-16 15:04:55.717 32306-20762/? E/XXX: Going to delete [alt.com.google.android.gms.devicedoctor, tayb125.ta@gmail.com, 208]
2018-11-16 15:04:55.718 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_api_early_update, , 3]
2018-11-16 15:04:55.719 32306-20762/? E/XXX: Going to delete [com.google.android.gms.auth_api_early_update, tayb125.ta@gmail.com, 3]
2018-11-16 15:04:55.720 32306-20762/? E/XXX: Going to delete [com.google.android.gms.locationsharing, , 212]
2018-11-16 15:04:55.721 32306-20762/? E/XXX: Going to delete [com.google.android.gms.locationsharing, tayb125.ta@gmail.com, 212]
2018-11-16 15:04:55.722 32306-20762/? E/XXX: Going to delete [com.google.android.apps.maps, , 985201143]
2018-11-16 15:04:55.723 32306-20762/? E/XXX: Going to delete [com.google.android.apps.maps, tayb125.ta@gmail.com, 985201143]
2018-11-16 15:04:55.725 32306-20762/? E/XXX: Going to delete [com.google.oauthintegrations#com.google.android.apps.maps, , 17]
2018-11-16 15:04:55.726 32306-20762/? E/XXX: Going to delete [com.google.oauthintegrations#com.google.android.apps.maps, tayb125.ta@gmail.com, 17]
2018-11-16 15:04:55.726 32306-20762/? E/XXX: Going to delete [com.google.android.gms.semanticlocation, , 105]
2018-11-16 15:04:55.728 32306-20762/? E/XXX: Going to delete [com.google.android.gms.semanticlocation, tayb125.ta@gmail.com, 105]
2018-11-16 15:04:55.729 32306-20762/? E/XXX: Going to delete [com.google.android.gms.notifications, , 209]
2018-11-16 15:04:55.730 32306-20762/? E/XXX: Going to delete [com.google.android.gms.notifications, tayb125.ta@gmail.com, 209]
2018-11-16 15:04:55.731 32306-20762/? E/XXX: Going to delete [com.google.android.gms.vision, , 1800]
2018-11-16 15:04:55.732 32306-20762/? E/XXX: Going to delete [com.google.android.gms.vision, tayb125.ta@gmail.com, 1800]
2018-11-16 15:04:55.733 32306-20762/? E/XXX: Going to delete [com.google.android.gms.vision.sdk, , 1800]
2018-11-16 15:04:55.734 32306-20762/? E/XXX: Going to delete [com.google.android.gms.vision.sdk, tayb125.ta@gmail.com, 1800]
2018-11-16 15:04:55.735 32306-20762/? E/XXX: Going to delete [com.google.android.gms.fonts, , 226]
2018-11-16 15:04:55.737 32306-20762/? E/XXX: Going to delete [com.google.android.gms.fonts, tayb125.ta@gmail.com, 226]
2018-11-16 15:04:55.738 32306-20762/? E/XXX: Going to delete [com.google.android.gm, , 60362688]
2018-11-16 15:04:55.742 32306-20762/? E/XXX: Going to delete [com.google.android.gm, tayb125.ta@gmail.com, 60362688]
2018-11-16 15:04:55.743 32306-20762/? E/XXX: Going to delete [com.google.android.apps.tachyon, , 2263968]
2018-11-16 15:04:55.760 32306-20762/? E/XXX: Going to delete [com.google.android.apps.tachyon, tayb125.ta@gmail.com, 2263968]
2018-11-16 15:04:55.765 32306-20762/? E/XXX: Going to delete [com.google.apps.drive.android, , 181520134]
2018-11-16 15:04:55.767 4720-4804/? E/WindowManager: win=Window{4fb27ff u0 com.malik.testapplication/com.malik.testapplication.ViewDirections EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0, caller=com.android.server.wm.AppWindowToken.destroySurfaces:748 com.android.server.wm.AppWindowToken.destroySurfaces:732 com.android.server.wm.WindowState.onExitAnimationDone:5523 com.android.server.wm.AppWindowAnimator.stepAnimationLocked:517 com.android.server.wm.TaskStack.stepAppWindowsAnimation:2018
答案 0 :(得分:0)
getLastLocation()
方法可以返回null。
因此,您在此行上遇到了NullPointerException
val origin = StringBuilder(mLastLocation!!.latitude.toString())