Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Kotlin-为什么我在谷歌地图的moveCamera上得到KotlinNullPointerException_Android_Android Studio_Kotlin - Fatal编程技术网

Android Kotlin-为什么我在谷歌地图的moveCamera上得到KotlinNullPointerException

Android Kotlin-为什么我在谷歌地图的moveCamera上得到KotlinNullPointerException,android,android-studio,kotlin,Android,Android Studio,Kotlin,这是我第一次构建android应用程序。然而,当我在我的虚拟设备上运行应用程序时,当我点击两次链接到谷歌地图的按钮后,它停止工作并不断崩溃。该错误说明了空指针异常 输出结果如下所示: 2020-12-19 08:48:46.512 15643-15643/com.tech.redesma.logsheetdataassistantcepln E/AndroidRuntime:致命异常:main 流程:com.tech.redesma.logsheetdataassistancepln,PID:1

这是我第一次构建android应用程序。然而,当我在我的虚拟设备上运行应用程序时,当我点击两次链接到谷歌地图的按钮后,它停止工作并不断崩溃。该错误说明了空指针异常

输出结果如下所示:

2020-12-19 08:48:46.512 15643-15643/com.tech.redesma.logsheetdataassistantcepln E/AndroidRuntime:致命异常:main 流程:com.tech.redesma.logsheetdataassistancepln,PID:15643 kotlin.KotlinNullPointerException 在com.tech.redesma.logsheetdataassistancepln.MyNavigationActivity.moveCamera(MyNavigationActivity.kt:261)上 在com.tech.redesma.logsheetdataassistancepln.MyNavigationActivity.access$moveCamera(MyNavigationActivity.kt:31) 在com.tech.redesma.logsheetdataassistancepln.MyNavigationActivity$getCurrentLocation$1.onComplete(MyNavigationActivity.kt:241) 位于com.google.android.gms.tasks.zzj.run(未知来源) 位于android.os.Handler.handleCallback(Handler.java:754) 位于android.os.Handler.dispatchMessage(Handler.java:95) 位于android.os.Looper.loop(Looper.java:165) 位于android.app.ActivityThread.main(ActivityThread.java:6375) 位于java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)上 位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)

以下是Kotlin代码:

package com.tech.redesma.logsheetdataassistancepln

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import com.github.florent37.runtimepermission.kotlin.askPermission
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import kotlinx.android.synthetic.main.activity_my_navigation.*
import java.io.IOException
import java.util.*

class MyNavigationActivity : AppCompatActivity(), OnMapReadyCallback
//        , LocationListener, GoogleMap.OnCameraMoveListener, GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraIdleListener
{

    private var mMap: GoogleMap? = null

    lateinit var mapView: MapView

    private val MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey"

    private val DEFAULT_ZOOM = 15f

    lateinit var tvCurrentAddress: TextView

    private var fusedLocationProviderClient : FusedLocationProviderClient? = null

    var end_latitude = 0.0

    var end_longitude = 0.0

    var origin: MarkerOptions? = null

    var destination:MarkerOptions? = null

    var latitude = 0.0

    var longitude = 0.0

    override fun onMapReady(googleMap: GoogleMap?) {

        mapView.onResume()
        mMap = googleMap

        askPermissionLocation()

        if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        mMap!!.setMyLocationEnabled(true)
//        mMap!!.setOnCameraMoveListener (this)
//        mMap!!.setOnCameraMoveStartedListener(this)
//        mMap!!.setOnCameraIdleListener(this)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_navigation)

        mapView = findViewById<MapView>(R.id.map1)

        tvCurrentAddress = findViewById<TextView>(R.id.tvAdd)

        askPermissionLocation()

        var mapViewBundle: Bundle? = null
        if(savedInstanceState != null) {
            mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY)
        }

        mapView.onCreate(mapViewBundle)
        mapView.getMapAsync(this)

        B_search.setOnClickListener {

            searchArea()
        }

    }

    private fun searchArea() {
        val tf_location =
            findViewById<View>(R.id.TF_location) as EditText

        val location = tf_location.text.toString()

        var addressList: List<Address>? = null

        val markerOptions = MarkerOptions()

        if (location != "") {
            val geocoder = Geocoder (applicationContext)
            try {
                addressList = geocoder.getFromLocationName(location, 5)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            if (addressList != null) {
                for (i in addressList.indices) {
                    val myAddress = addressList[i]
                    val latLng =
                            LatLng(myAddress.latitude, myAddress.longitude)
                    markerOptions.position(latLng)
                    mMap!!.addMarker(markerOptions)
                    end_latitude = myAddress.latitude
                    end_longitude = myAddress.longitude

                    mMap!!.animateCamera(CameraUpdateFactory.newLatLng(latLng))

                    val mo = MarkerOptions()
                    mo.title("Distance")

                    val results = FloatArray(10)
                    Location.distanceBetween(
                            latitude,
                            longitude,
                            end_latitude,
                            end_longitude,
                            results
                    )

                    val s =
                        String.format("%.1f", results[0] / 1000)


                    //Setting marker to draw route between these two points
                    origin = MarkerOptions().position(LatLng(latitude, longitude))
                            .title("HSR Layout").snippet("origin")
                    destination =
                            MarkerOptions().position(LatLng(end_latitude, end_longitude))
                                    .title(tf_location.text.toString())
                                    .snippet("Distance = $s KM")
                    mMap!!.addMarker(destination)
                    mMap!!.addMarker(origin)

                    Toast.makeText(
                            this@MyNavigationActivity,
                            "Distance = $s KM",
                            Toast.LENGTH_SHORT
                    ) .show()


                    tvCurrentAddress!!.setText("Distance = $s KM")
                }
            }
        }
    }

    public override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        askPermissionLocation()
        var mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY)
        if (mapViewBundle == null){
            mapViewBundle = Bundle()
            outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle)
        }

        mapView.onSaveInstanceState(mapViewBundle)
    }

    private fun askPermissionLocation(){
        askPermission(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        ){

            getCurrentLocation()
//            mapView.getMapAsync(this@MyNavigationActivity)

        } .onDeclined {e ->
            if (e.hasDenied()){
                //the list of denied permissions
                e.denied.forEach {
                }

                AlertDialog.Builder(this)
                        .setMessage("Please accept our permission.. Otherwise you will not be able to use some of our Important Features.")
                        .setPositiveButton("yes") { _, _ ->
                            e.askAgain()
                        } //ask again
                        .setNegativeButton("no") { dialog, _ ->
                            dialog.dismiss()
                        }
                        .show()
            }

            if (e.hasForeverDenied()) {
                // the list of forever denied permissions, user has check 'never ask again'
                e.foreverDenied.forEach{
                }
                // you need to open setting manually if you really need it
                e.goToSettings();
            }
        }

    }

    private fun getCurrentLocation() {
        fusedLocationProviderClient =
            LocationServices.getFusedLocationProviderClient(this@MyNavigationActivity)

        try {
            @SuppressLint ("MissingPermission")
            val location =
                    fusedLocationProviderClient!!.getLastLocation()

            location.addOnCompleteListener(object : OnCompleteListener<Location> {
                override fun onComplete(loc: Task<Location>) {
                    if (loc.isSuccessful) {

                        val currentLocation = loc.result as Location?
                        if (currentLocation != null) {
                            moveCamera(
                                 LatLng(currentLocation.latitude, currentLocation.longitude),
                                 DEFAULT_ZOOM
                            )

                            latitude = currentLocation.latitude
                            longitude = currentLocation.longitude

                        }
                    } else {
                       askPermissionLocation()
                    }
                }
            })
        } catch (se: Exception) {
            Log.e("TAG", "Security Exception")
        }
    }

    private fun moveCamera(latLng: LatLng, zoom: Float) {
        mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))
    }


//    override fun onLocationChanged(location: Location?) {
//       val geocoder = Geocoder (this, Locale.getDefault())
//       var addresses: List<Address>? = null
//       try {
//           addresses = geocoder.getFromLocation(location!!.latitude, location.longitude, 1)
//       } catch (e: IOException) {
//           e.printStackTrace()
//       }
//       setAddress(addresses!![0])
//    }
//
//    private fun setAddress(addresses: Address) {
//        if (addresses != null) {
//
//            if (addresses.getAddressLine(0) != null) {
//                tvCurrentAddress!!.setText(addresses.getAddressLine(0))
//            }
//            if (addresses.getAddressLine(1) != null) {
//                tvCurrentAddress!!.setText(
//                        tvCurrentAddress.getText().toString() + addresses.getAddressLine(1)
//                )
//            }
//        }
//    }
//
//
//
//    override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
//
//    }
//
//    override fun onProviderEnabled(p0: String?) {
//
//    }
//
//    override fun onProviderDisabled(p0: String?) {
//
//    }
//
//    override fun onCameraMove() {
//
//    }
//
//    override fun onCameraMoveStarted(p0: Int) {
//
//    }
//
//    override fun onCameraIdle() {
//        var addresses: List<Address>? = null
//        val geocoder = Geocoder (this, Locale.getDefault())
//        try {
//            addresses = geocoder.getFromLocation( mMap!!.getCameraPosition().target.latitude, mMap!!.getCameraPosition().target.longitude, 1)
//
//            setAddress(addresses!![0])
//
//        } catch (e: IndexOutOfBoundsException) {
//            e.printStackTrace()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//    }
}
package com.tech.redesma.logsheetdataassistancepln
导入android.Manifest
导入android.annotation.SuppressLint
导入android.content.pm.PackageManager
导入android.location.Address
导入android.location.Geocoder
导入android.location.location
导入android.location.LocationListener
导入androidx.appcompat.app.appcompat活动
导入android.os.Bundle
导入android.util.Log
导入android.view.view
导入android.widget.EditText
导入android.widget.TextView
导入android.widget.Toast
导入androidx.appcompat.app.AlertDialog
导入androidx.core.app.ActivityCompat
导入com.github.florent37.runtimepermission.kotlin.askPermission
导入com.google.android.gms.location.FusedLocationProviderClient
导入com.google.android.gms.location.LocationServices
导入com.google.android.gms.maps*
导入com.google.android.gms.maps.model.LatLng
导入com.google.android.gms.maps.model.MarkerOptions
导入com.google.android.gms.tasks.OnCompleteListener
导入com.google.android.gms.tasks.Task
导入kotlinx.android.synthetic.main.activity\u my\u导航*
导入java.io.IOException
导入java.util*
类MyNavigationActivity:AppCompatActivity(),OnMapReadyCallback
//,LocationListener,GoogleMap.OnCameraMoveListener,GoogleMap.OnCameraMoveStartedListener,GoogleMap.OnCameraDelListener
{
私有变量mMap:GoogleMap?=null
lateinit var映射视图:映射视图
私有val映射\u视图\u绑定\u KEY=“MapViewBundleKey”
私有值默认值_缩放=15f
lateinit变量tvCurrentAddress:TextView
私有变量fusedLocationProviderClient:fusedLocationProviderClient?=null
var end_纬度=0.0
var end_经度=0.0
变量来源:MarkerOptions?=null
var目标:标记选项?=null
var纬度=0.0
var经度=0.0
在mapready上覆盖乐趣(谷歌地图:谷歌地图?){
onResume()文件
mMap=谷歌地图
askPermissionLocation()
如果(ActivityCompat.checkSelfPermission(
这
Manifest.permission.ACCESS\u FINE\u位置
)!=PackageManager.PERMISSION\u已授予和&ActivityCompat.checkSelfPermission(
这
Manifest.permission.ACCESS\u位置
)!=已授予PackageManager.PERMISSION\u权限
) {
返回
}
mMap!!.setMyLocationEnabled(真)
//mMap!!.setOnCameraMoveListener(此)
//mMap!!.setOnCameraMoveStartedListener(此)
//mMap!!.setonCameraideListener(此)
}
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u my\u导航)
mapView=findViewById(R.id.map1)
tvCurrentAddress=findViewById(R.id.tvAdd)
askPermissionLocation()
var mapViewBundle:Bundle?=null
如果(savedInstanceState!=null){
mapViewBundle=savedInstanceState.getBundle(映射\视图\捆绑\键)
}
onCreate(mapViewBundle)
getMapAsync(此)
B_search.setOnClickListener{
搜索区域()
}
}
私人娱乐搜索区(){
val tf_位置=
findViewById(R.id.TF_位置)作为EditText
val location=tf_location.text.toString()
var地址列表:列表?=null
val markerOptions=markerOptions()
如果(位置!=“”){
val geocoder=geocoder(applicationContext)
试一试{
addressList=geocoder.getFromLocationName(位置,5)
}捕获(e:IOException){
e、 printStackTrace()
}
如果(地址列表!=null){
对于(地址列表索引中的i){
val myAddress=地址列表[i]
瓦拉廷酒店=
LatLng(myAddress.latitude,myAddress.latitude)
标记选项位置(车床)
mMap!!.addMarker(markerOptions)
end_纬度=myAddress.latitude
end_longitude=myAddress.longitude
mMap!!.animateCamera(CameraUpdateFactory.newLatLng(latLng))
val mo=标记选项()
mo.title(“距离”)
val结果=浮点数组(10)
位置,距离(
纬度,
经度,
结束纬度,