I've recently encountered an extremly strange proble while developing my simple location based app.
Basically, what I'm trying to achieve is getting LatLng
object from OnMapClickListener
, saving its latitude
and longitude
into Room using Dao, and then retrieving them in some other object (fusedLocationProviderClient
`s locationCallback to be exact).
Destination - a simple Room Entity which has lat, lng, and timestamp as a primary key.
@Entity(tableName = "destinations")
data class Destination(
@PrimaryKey var timestamp: Long = 0L,
var lat: Double = -1.0,
var long: Double = -1.0
)
DestinationDao - to access Room.
@Dao
interface DestinationDao {
// Get the newest destination
@Query("SELECT * FROM destinations WHERE timestamp = (SELECT MAX(timestamp) FROM destinations)")
fun getDestination(): Destination?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertDestination(destination: Destination)
}
MapsActivity - the place where I get coordinates from user click and save them into SQLite using Room
map.setOnMapClickListener { latLng ->
val destination = Destination(System.nanoTime(), lat = latLng.latitude, long = latLng.longitude)
Log.d(TAG, destination.toString())
AppDatabase.getInstance(this).destinationDao().insertDestination(destination)
Log.d(TAG, AppDatabase.getInstance(this).destinationDao().getDestination().toString())
}
MyLocationListener - the place where I retrieve my coordinates from Room
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(userLocation: LocationResult?) {
val array = FloatArray(1)
val destination = AppDatabase.getInstance(appContext).destinationDao().getDestination()
Log.d(TAG, "Distance: ${array[0]} m\nlat: ${destination!!.lat}, long: ${destination.long}")
}
}
It seems simple, but for an unknown reason, longitude never gets saved to Room! To better illustrate this, here are the logs from that MapsActivity
snippet (-1.0 is a default value)
// Destination created from `LatLng` object from map click listener
D/MapsActivity: Destination(timestamp=248767407310345, lat=50.1813350498603, long=18.45104455947876)
// Destination retrieved from Room
D/MapsActivity: Destination(timestamp=248767407310345, lat=50.1813350498603, long=-1.0)
I have completely no idea why is that. I tried changing Double to String and then parsing it, tried reducing the count of decimal places, I even tried changing the order of variables declaration in Destination
class - nothing works.
If any additional data is needed, I'll post it. Thank you in advance.
It may be so, because you called you longitude variable - long! "Long" is reserved word in Java, not in Kotlin, I know, but, what if you try to change this row:
var long: Double = -1.0
to
var longitude: Double = -1.0