kotlinandroid-geofence

Struggling with a list geofenceList in Kotlin


I tracked my problem down to adding to my geofenceList.

this is a global variable

lateinit var geofenceList: MutableList<Geofence>

In onCreate I add to the list:

val latitude = -26.082586
val longitude = 27.777242
val radius = 10f
geofenceList.add(Geofence.Builder()
      .setRequestId("Toets")
      .setCircularRegion(latitude,longitude,radius)
      .setExpirationDuration(Geofence.NEVER_EXPIRE)
      .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
      .build())

Every time I run the app the app closes as soon as it opens.

I tried changing it to a normal variable but I am not certain how to do it and keep it a global variable, and a List would be more useful.


Solution

  • I just realized what your issue is: You never initialize your list. When you follow the advice in my comment, you should find a NullPointerException and here's how to fix it:

    Firstly, try to avoid lateinit if possible. The compiler actually tries to find this problem for you and by using lateinit, you basically tell the compiler to shut up - even though the mistake is still there. INstead, you need to initialize your variable like so:

    var geofenceList: MutableList<Geofence> = mutableListOf()
    

    You could make it even shorter by removing the explicit type declaration:

    var geofenceList = mutableListOf<Geofence>()