我正在try 将LatLng对象的数组列表传递给另一个活动.该方法是在不是活动的Util类中定义的.但接受活动总是筹集NullpointerException
美元
class Utils {
companion object {
fun startMaps(pairs: MutableList<LatLng>){
var intent = Intent(AAddressActivity.appContext, MapActivity::class.java)
Log.d("pair", ArrayList(pairs).toString())
Log.d("pair", ArrayList(pairs)[0].toString())
intent.putParcelableArrayListExtra("key", ArrayList(pairs))
AAddressActivity.appContext.startActivity(intent)
}
}
Log.d
打印非空对的内容./AAddressActivity.appContext
其中AAddressActivity是调用Utils.startMap()
方法的活动,appContext
定义为
companion object{
lateinit var appContext: Context
}
并在onCreate() AAddressActivity
AS appContext=this
中进行初始化,以允许外部访问AAddressActivity
的上下文.
这是接收活动:
class MapActivity : AppCompatActivity(), OnMapReadyCallback {
lateinit var latLngList: ArrayList<LatLng>
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
// Error happens here
latLngList = intent.getParcelableArrayListExtra("key", LatLng::class.java)!!
Log.d("longMap", latLngList[0].toString())
}
错误是
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidapplicationproject/com.example.androidapplicationproject.mapUtil.MapActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Class.isInterface()' on a null object reference
As far as I know, LatLng object implements Parcelable so I shouldn't worry about that. But why is the error happening? How do I fix it.
I just found that if there are only ONE element in the pairs
then the MapActivity
can successfully receive the parcel, but if there are two or more elements in the list, the exception raises.