PolylineOptions не может иметь значение null, и маршрут не отображается - PullRequest
0 голосов
/ 26 мая 2020

Мне нужна ваша помощь, я пытаюсь создать приложение в Kotlin на Android Studio, но у меня проблема.

В части этого приложения я пытаюсь показать маршрут между два очка, но у меня ошибка. Вначале ошибка заключалась в том, что я получил «java .lang.NullPointerException: PolylineOptions не может быть нулевым». , я решаю ее, добавляя «if (polylineOptions! = null) {», но теперь проблема в том, что я не получаю никаких ошибок, но маршрут между двумя точками не отображается.

Здесь это код моего класса, озабоченного этой проблемой:

class ViewDirections : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

lateinit var mService: IGoogleAPIService

companion object { private const val MY_PERMISSION_CODE: Int = 1000 }

lateinit var mCurrentMarker: Marker

var polyLine:Polyline?=null

lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var locationRequest: LocationRequest
lateinit var locationCallback: LocationCallback
lateinit var mLastLocation:Location

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_view_direction)
    // 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.googleApiServiceScalars

    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())
    }

}

private fun checkLocationPermission(): Boolean {
    if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                ViewDirections.MY_PERMISSION_CODE
            )
        else
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                ViewDirections.MY_PERMISSION_CODE
            )
        return false
    }
    else
    {
        return true
    }
}

//override onRequestPermissionResult
@RequiresApi(Build.VERSION_CODES.M)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    when(requestCode)
    {
        ViewDirections.MY_PERMISSION_CODE ->{
            if(grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                if(ContextCompat.checkSelfPermission(this, android.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 Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

private fun buildLocationRequest() {
    locationRequest = LocationRequest()
    locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    locationRequest.interval = 5000
    locationRequest.fastestInterval = 3000
    locationRequest.smallestDisplacement = 10f

    //Toast.makeText(applicationContext, "latitude: $latitude \n longitude : $longitude", Toast.LENGTH_LONG).show()
}

private fun buildLocationCallBack() {
    locationCallback = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            mLastLocation = p0!!.lastLocation

            val markerOptions = MarkerOptions()
                .position(LatLng(mLastLocation.latitude, mLastLocation.longitude))
                .title("Votre position")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))

            mCurrentMarker = mMap!!.addMarker(markerOptions)

            mMap!!.moveCamera(CameraUpdateFactory.newLatLng(LatLng(mLastLocation.latitude, mLastLocation.longitude)))
            mMap!!.animateCamera(CameraUpdateFactory.zoomTo(12.0f))

            //Position destination
            val destinationLatLng = LatLng(Common.currentResult!!.geometry!!.location!!.lat.toDouble(),
                Common.currentResult!!.geometry!!.location!!.lng.toDouble())

            mMap!!.addMarker(MarkerOptions().position(destinationLatLng)
                .title(Common.currentResult!!.name)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)))

            //Itineraire
            drawPath(mLastLocation, Common.currentResult!!.geometry!!.location!!)

        }
    }
}

private fun drawPath(mLastLocation: Location?, location: com.example.finder.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("FINDER", t.message)
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                ParserTask().execute(response!!.body()!!.toString())
            }
        })
}

override fun onStop() {
    fusedLocationProviderClient.removeLocationUpdates(locationCallback)
    super.onStop()
}

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("Votre position")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))

        mCurrentMarker = mMap!!.addMarker(markerOptions)

        mMap!!.moveCamera(CameraUpdateFactory.newLatLng(LatLng(mLastLocation.latitude, mLastLocation.longitude)))
        mMap!!.animateCamera(CameraUpdateFactory.zoomTo(12.0f))

        //Position destination
        val destinationLatLng = LatLng(Common.currentResult!!.geometry!!.location!!.lat.toDouble(),
            Common.currentResult!!.geometry!!.location!!.lng.toDouble())

        mMap!!.addMarker(MarkerOptions().position(destinationLatLng)
            .title(Common.currentResult!!.name)
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)))

        //Itineraire
        drawPath(mLastLocation, Common.currentResult!!.geometry!!.location!!)
    }
}

inner class ParserTask:AsyncTask<String,Int,List<List<HashMap<String,String>>>>(){
    internal val waitingDialog = SpotsDialog(this@ViewDirections)

    override fun onPreExecute() {
        super.onPreExecute()
        waitingDialog.show()
        waitingDialog.setMessage("Veuillez patienter...")
    }

    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>?=null
        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)

        }

        if(polylineOptions != null){
            mMap!!.addPolyline(polylineOptions)
        }

        waitingDialog.dismiss()

    }

}

}

И вот журнал, когда я запускаю приложение, пока я не попытаюсь получить маршрут:

05/26 13:03:56: Launching 'app' on SELECLINE S3T10IN.
$ adb shell am start -n "com.example.finder/com.example.finder.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 13379 on device 'selecline-s3t10in-86649d48090700000000'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/MultiDex: VM with version 2.1.0 has multidex support
I/MultiDex: Installing application
I/MultiDex: VM has multidex support, MultiDex support library is disabled.
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
W/art: Suspending all threads took: 32.548ms
I/art: Background sticky concurrent mark sweep GC freed 1591(87KB) AllocSpace objects, 0(0B) LOS objects, 3% free, 3MB/3MB, paused 43.151ms total 74.669ms
I/art: Background partial concurrent mark sweep GC freed 118(29KB) AllocSpace objects, 0(0B) LOS objects, 40% free, 3MB/5MB, paused 5.382ms total 69.205ms
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: false
D/Atlas: Validating map...
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
I/zzbz: Making Creator dynamically
I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:201816000
    Selected remote version of com.google.android.gms.maps_dynamite, version >= 201816000
W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
W/ResourcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
I/art: Background sticky concurrent mark sweep GC freed 9532(692KB) AllocSpace objects, 1(13KB) LOS objects, 14% free, 4MB/5MB, paused 3.301ms total 111.495ms
I/Google Maps Android API: Google Play services client version: 11910000
I/Google Maps Android API: Google Play services package version: 201816006
W/ContextImpl: Failed to ensure directory: /storage/extsd/Android/data/com.example.finder/cache
I/art: Background sticky concurrent mark sweep GC freed 17115(1414KB) AllocSpace objects, 7(245KB) LOS objects, 15% free, 6MB/8MB, paused 19.120ms total 132.593ms
D/URL_DEBUG: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=50.7283825,1.6183893&radius=10000&type=bar&key=****************************************
I/art: Background sticky concurrent mark sweep GC freed 9615(404KB) AllocSpace objects, 4(281KB) LOS objects, 7% free, 7MB/8MB, paused 6.019ms total 53.619ms
I/art: Background sticky concurrent mark sweep GC freed 8022(287KB) AllocSpace objects, 1(64KB) LOS objects, 4% free, 7MB/8MB, paused 6.407ms total 49.642ms
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
    Selected remote version of com.google.android.gms.googlecertificates, version >= 4
I/art: Background sticky concurrent mark sweep GC freed 5268(222KB) AllocSpace objects, 1(128KB) LOS objects, 0% free, 8MB/8MB, paused 3.830ms total 104.154ms
I/art: Background partial concurrent mark sweep GC freed 11375(617KB) AllocSpace objects, 21(743KB) LOS objects, 40% free, 7MB/12MB, paused 5.845ms total 103.471ms
I/Google Maps Android API: Google Play services package version: 201816006
I/art: Background sticky concurrent mark sweep GC freed 18537(791KB) AllocSpace objects, 11(1408KB) LOS objects, 17% free, 10MB/12MB, paused 10.169ms total 114.008ms
I/art: Background partial concurrent mark sweep GC freed 18549(1020KB) AllocSpace objects, 75(2MB) LOS objects, 39% free, 9MB/16MB, paused 3.162ms total 110.832ms

Кто-нибудь из вас знает, почему мой маршрут не отображается, или в чем проблема? Спасибо

...