- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要做什么
当我的应用程序启动时,我正在使用一个使用 AutoCompleteTextView
的 fragment 和 Places SDK 获取 Place
用户进行选择时的对象。发生这种情况时,我通过调用 repository.storeWeatherLocation(context,placeId)
将所选地点(作为 WeatherLocation 实体)存储在我的 Room 数据库中的 Repository 类中。然后在需要时再次获取天气详细信息。
发生了什么 suspend fun storeWeatherLocationAsync
正在调用fetchCurrentWeather()
& fetchWeeklyWeather()
因为根据我的记录,previousLocation
尽管数据库检查器显示较旧的天气位置数据已经存在,但变量为空。
崩溃详情
我的应用程序崩溃了,说明我的 LocationProvider 的 getCustomLocationLat()
正在返回 null(发生在 fetchCurrentWeather()
中)。问题是用户选择的位置已成功存储在我的 Room 数据库中(使用 Database Inspector 检查),那么这个函数如何返回 null?
更新 :
在使用调试器和 logcat 进行更多测试后,我发现 WeatherLocation
应用程序运行时,数据正在保存在 Room 中。一旦它崩溃并且我重新打开它,该数据再次为空。我在这里想念什么?我是否以某种方式删除了以前的数据?我实际上没有在 Room 中正确缓存它吗?
数据库类:
@Database(
entities = [CurrentWeatherEntry::class,WeekDayWeatherEntry::class,WeatherLocation::class],
version = 16
)
abstract class ForecastDatabase : RoomDatabase() {
abstract fun currentWeatherDao() : CurrentWeatherDao
abstract fun weekDayWeatherDao() : WeekDayWeatherDao
abstract fun weatherLocationDao() : WeatherLocationDao
// Used to make sure that the ForecastDatabase class will be a singleton
companion object {
// Volatile == all of the threads will have immediate access to this property
@Volatile private var instance:ForecastDatabase? = null
private val LOCK = Any() // dummy object for thread monitoring
operator fun invoke(context:Context) = instance ?: synchronized(LOCK) {
// If the instance var hasn't been initialized, call buildDatabase()
// and assign it the returned object from the function call (it)
instance ?: buildDatabase(context).also { instance = it }
}
/**
* Creates an instance of the ForecastDatabase class
* using Room.databaseBuilder().
*/
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
ForecastDatabase::class.java, "forecast.db")
//.addMigrations(MIGRATION_2_3) // specify an explicit Migration Technique
.fallbackToDestructiveMigration()
.build()
}
}
这是存储库类:
class ForecastRepositoryImpl(
private val currentWeatherDao: CurrentWeatherDao,
private val weekDayWeatherDao: WeekDayWeatherDao,
private val weatherLocationDao: WeatherLocationDao,
private val locationProvider: LocationProvider,
private val weatherNetworkDataSource: WeatherNetworkDataSource
) : ForecastRepository {
init {
weatherNetworkDataSource.apply {
// Persist downloaded data
downloadedCurrentWeatherData.observeForever { newCurrentWeather: CurrentWeatherResponse? ->
persistFetchedCurrentWeather(newCurrentWeather!!)
}
downloadedWeeklyWeatherData.observeForever { newWeeklyWeather: WeeklyWeatherResponse? ->
persistFetchedWeeklyWeather(newWeeklyWeather!!)
}
}
}
override suspend fun getCurrentWeather(): LiveData<CurrentWeatherEntry> {
return withContext(Dispatchers.IO) {
initWeatherData()
return@withContext currentWeatherDao.getCurrentWeather()
}
}
override suspend fun getWeekDayWeatherList(time: Long): LiveData<out List<WeekDayWeatherEntry>> {
return withContext(Dispatchers.IO) {
initWeatherData()
return@withContext weekDayWeatherDao.getFutureWeather(time)
}
}
override suspend fun getWeatherLocation(): LiveData<WeatherLocation> {
return withContext(Dispatchers.IO) {
return@withContext weatherLocationDao.getWeatherLocation()
}
}
private suspend fun initWeatherData() {
// retrieve the last weather location from room
val lastWeatherLocation = weatherLocationDao.getWeatherLocation().value
if (lastWeatherLocation == null ||
locationProvider.hasLocationChanged(lastWeatherLocation)
) {
fetchCurrentWeather()
fetchWeeklyWeather()
return
}
val lastFetchedTime = currentWeatherDao.getCurrentWeather().value?.zonedDateTime
if (isFetchCurrentNeeded(lastFetchedTime!!))
fetchCurrentWeather()
if (isFetchWeeklyNeeded())
fetchWeeklyWeather()
}
/**
* Checks if the current weather data should be re-fetched.
* @param lastFetchedTime The time at which the current weather data were last fetched
* @return True or false respectively
*/
private fun isFetchCurrentNeeded(lastFetchedTime: ZonedDateTime): Boolean {
val thirtyMinutesAgo = ZonedDateTime.now().minusMinutes(30)
return lastFetchedTime.isBefore(thirtyMinutesAgo)
}
/**
* Fetches the Current Weather data from the WeatherNetworkDataSource.
*/
private suspend fun fetchCurrentWeather() {
weatherNetworkDataSource.fetchCurrentWeather(
locationProvider.getPreferredLocationLat(),
locationProvider.getPreferredLocationLong()
)
}
private fun isFetchWeeklyNeeded(): Boolean {
val todayEpochTime = LocalDate.now().toEpochDay()
val futureWeekDayCount = weekDayWeatherDao.countFutureWeekDays(todayEpochTime)
return futureWeekDayCount < WEEKLY_FORECAST_DAYS_COUNT
}
private suspend fun fetchWeeklyWeather() {
weatherNetworkDataSource.fetchWeeklyWeather(
locationProvider.getPreferredLocationLat(),
locationProvider.getPreferredLocationLong()
)
}
override fun storeWeatherLocation(context:Context,placeId: String) {
GlobalScope.launch(Dispatchers.IO) {
storeWeatherLocationAsync(context,placeId)
}
}
override suspend fun storeWeatherLocationAsync(context: Context,placeId: String) {
var isFetchNeeded: Boolean // a flag variable
// Specify the fields to return.
val placeFields: List<Place.Field> =
listOf(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG)
// Construct a request object, passing the place ID and fields array.
val request = FetchPlaceRequest.newInstance(placeId, placeFields)
// Create the client
val placesClient = Places.createClient(context)
placesClient.fetchPlace(request).addOnSuccessListener { response ->
// Get the retrieved place object
val place = response.place
// Create a new WeatherLocation object using the place details
val newWeatherLocation = WeatherLocation(place.latLng!!.latitude,
place.latLng!!.longitude,place.name!!,place.id!!)
val previousLocation = weatherLocationDao.getWeatherLocation().value
if(previousLocation == null || ((newWeatherLocation.latitude != previousLocation.latitude) &&
(newWeatherLocation.longitude != previousLocation.longitude))) {
isFetchNeeded = true
// Store the weatherLocation in the database
persistWeatherLocation(newWeatherLocation)
// fetch the data
GlobalScope.launch(Dispatchers.IO) {
// fetch the weather data and wait for it to finish
withContext(Dispatchers.Default) {
if (isFetchNeeded) {
// fetch the weather data using the new location
fetchCurrentWeather()
fetchWeeklyWeather()
}
}
}
}
Log.d("REPOSITORY","storeWeatherLocationAsync : inside task called")
}.addOnFailureListener { exception ->
if (exception is ApiException) {
// Handle error with given status code.
Log.e("Repository", "Place not found: ${exception.statusCode}")
}
}
}
/**
* Caches the downloaded current weather data to the local
* database.
* @param fetchedCurrentWeather The most recently fetched current weather data
*/
private fun persistFetchedCurrentWeather(fetchedCurrentWeather: CurrentWeatherResponse) {
fetchedCurrentWeather.currentWeatherEntry.setTimezone(fetchedCurrentWeather.timezone)
// Using a GlobalScope since a Repository class doesn't have a lifecycle
GlobalScope.launch(Dispatchers.IO) {
currentWeatherDao.upsert(fetchedCurrentWeather.currentWeatherEntry)
}
}
/**
* Caches the selected location data to the local
* database.
* @param fetchedLocation The most recently fetched location data
*/
private fun persistWeatherLocation(fetchedLocation: WeatherLocation) {
GlobalScope.launch(Dispatchers.IO) {
weatherLocationDao.upsert(fetchedLocation)
}
}
/**
* Caches the downloaded weekly weather data to the local
* database.
* @param fetchedWeeklyWeather The most recently fetched weekly weather data
*/
private fun persistFetchedWeeklyWeather(fetchedWeeklyWeather: WeeklyWeatherResponse) {
fun deleteOldData() {
val time = LocalDate.now().toEpochDay()
weekDayWeatherDao.deleteOldEntries(time)
}
GlobalScope.launch(Dispatchers.IO) {
deleteOldData()
val weekDayEntriesList = fetchedWeeklyWeather.weeklyWeatherContainer.weekDayEntries
weekDayWeatherDao.insert(weekDayEntriesList)
}
}
}
这是 LocationProvider impl:
class LocationProviderImpl(
private val fusedLocationProviderClient: FusedLocationProviderClient,
context: Context,
private val locationDao: WeatherLocationDao
) : PreferenceProvider(context), LocationProvider {
private val appContext = context.applicationContext
override suspend fun hasLocationChanged(lastWeatherLocation: WeatherLocation): Boolean {
return try {
hasDeviceLocationChanged(lastWeatherLocation)
} catch (e:LocationPermissionNotGrantedException) {
false
}
}
/**
* Makes the required checks to determine whether the device's location has
* changed or not.
* @param lastWeatherLocation The last known user selected location
* @return true if the device location has changed or false otherwise
*/
private suspend fun hasDeviceLocationChanged(lastWeatherLocation: WeatherLocation): Boolean {
if(!isUsingDeviceLocation()) return false // we don't have location permissions or setting's disabled
val currentDeviceLocation = getLastDeviceLocationAsync().await()
?: return false
// Check if the old and new locations are far away enough that an update is needed
val comparisonThreshold = 0.03
return abs(currentDeviceLocation.latitude - lastWeatherLocation.latitude) > comparisonThreshold
&& abs(currentDeviceLocation.longitude - lastWeatherLocation.longitude) > comparisonThreshold
}
/**
* Checks if the app has the location permission, and if that's the case
* it will fetch the device's last saved location.
* @return The device's last saved location as a Deferred<Location?>
*/
@SuppressLint("MissingPermission")
private fun getLastDeviceLocationAsync(): Deferred<Location?> {
return if(hasLocationPermission())
fusedLocationProviderClient.lastLocation.asDeferredAsync()
else
throw LocationPermissionNotGrantedException()
}
/**
* Checks if the user has granted the location
* permission.
*/
private fun hasLocationPermission(): Boolean {
return ContextCompat.checkSelfPermission(appContext,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
/**
* Returns the sharedPrefs value for the USE_DEVICE_LOCATION
* preference with a default value of "true".
*/
private fun isUsingDeviceLocation(): Boolean {
return preferences.getBoolean(USE_DEVICE_LOCATION_KEY,false)
}
private fun getCustomLocationLat() : Double {
val lat:Double? = locationDao.getWeatherLocation().value?.latitude
if(lat == null) Log.d("LOCATION_PROVIDER","lat is null = $lat")
return lat!!
}
private fun getCustomLocationLong():Double {
return locationDao.getWeatherLocation().value!!.longitude
}
override suspend fun getPreferredLocationLat(): Double {
if(isUsingDeviceLocation()) {
try {
val deviceLocation = getLastDeviceLocationAsync().await()
?: return getCustomLocationLat()
return deviceLocation.latitude
} catch (e:LocationPermissionNotGrantedException) {
return getCustomLocationLat()
}
} else {
return getCustomLocationLat()
}
}
override suspend fun getPreferredLocationLong(): Double {
if(isUsingDeviceLocation()) {
try {
val deviceLocation = getLastDeviceLocationAsync().await()
?: return getCustomLocationLong()
return deviceLocation.longitude
} catch (e:LocationPermissionNotGrantedException) {
return getCustomLocationLong()
}
} else {
return getCustomLocationLong()
}
}
}
最佳答案
你不应该期待一个房间 LiveData
返回除 null
之外的任何内容来自 getValue()
直到 Observer
已添加并已在其回调中收到其第一个值。 LiveData
主要是一个可观察的数据持有者,而由 Room 创建的数据持有者在设计上都是惰性和异步的,因此它们不会开始执行后台数据库工作以使值可用,直到 Observer
被附上。
在这些情况下来自 LocationProviderImpl
:
private fun getCustomLocationLat() : Double {
val lat:Double? = locationDao.getWeatherLocation().value?.latitude
if(lat == null) Log.d("LOCATION_PROVIDER","lat is null = $lat")
return lat!!
}
private fun getCustomLocationLong():Double {
return locationDao.getWeatherLocation().value!!.longitude
}
Dao
具有更直接返回类型的方法来检索值,例如。在您的
Dao
而不是这样的:
@Query("<your query here>")
fun getWeatherLocation(): LiveData<LocationEntity>
@Query("<your query here>")
suspend fun getWeatherLocation(): LocationEntity?
@Query("<your query here>")
fun getWeatherLocationSync(): LocationEntity?
关于android - Room Entity 的数据存储正确,但检索为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61385565/
即使从 androidx.room.Room 导入,Room.databaseBuilder() 也无法找到 Room 依赖项。 我为数据库制作了一个不同的 Kotlin 库,并在 Room 的 gr
我正在尝试迁移我们的项目以使用 Room,顺便说一句,我认为这是向前迈出的一大步。 我有以下结构: public class Entity extends BaseObservable { @
Here是房间数据库的官方文档。它包含以下代码 val db = Room.databaseBuilder( applicationContext, A
Here是房间数据库的官方文档。它包含以下代码 val db = Room.databaseBuilder( applicationContext, A
我有一张供用户使用的表。用户创建一个类别,然后将 Youtube 视频分配到该类别。我目前有一个用户表、类别表(用户 ID 外键)和 youtubevideo 表(用户 ID 外键、类别外键)。 我目
拥有三张 table 的 Android Room timestamp , index , details ,并且这三个都有 @PrimaryKey @ColumnInfo(name = "id")
让我们举一个基本的例子 用于存储用户的表 @Entity (tableName="users") class UsersEntity( @PrimaryKey val id var
想确认是否可以将实体 bean 绑定(bind)到表的部分列? 例子: 表“A”有列 id, col1, col2, col3, col4, col5, ... , col10 但是我只需要 id、c
问题 双向数据绑定(bind)允许您使用来自对象的数据自动填充 UI 组件,然后在用户编辑这些 UI 组件时自动更新对象。 当用户编辑 UI 组件时,有没有办法不仅自动更新内存中的对象,而且自动更新/
我在 Android Room 中使用可观察查询来触发更新,最终在底层数据发生变化时改变 UI。 有时这些查询涉及多个表,有时用户执行将新值插入到这些表中的操作。插入通常一个接一个地快速完成(即在不到
我想知道点击新房间后如何离开房间 我的页面是这样的。 左侧列表来自MySQL服务器,它获取我的聊天列表。每个房间名称都有 id 值,即房间名称。并且它还有onclick函数可以在客户端使用函数。 当我
我正在尝试将此模块化项目升级到最新的依赖项,但 gradle 构建失败并显示 could not resolve androidx.room:room-runtime:2.4.2我已经包含了maven
在使用 Kotlin Coroutines Flow、Room 和 Live Data 时,我面临着一个非常奇怪的行为。每当我关闭我的设备大约 5-10 秒然后重新打开它时,协程流程就会重新运行而没有
我正在与一位同事讨论我们部署的一款软件遇到的问题,他提到这与一段时间内预订房间的概念问题有何相似之处,算法应该输出房间需要最少开关的预订(因此,例如,最佳解决方案可能是在一个房间停留 3 天,其余时间
如何使用 Room Persistence 库“创建触发器” CREATE TRIGGER IF NOT EXISTS delete_till_10 INSERT ON user WHEN (sel
你如何在 Android Room 中使用 List 的 我有一个表实体,我想通过 Android Room 将其保存在我的 SQLDatabase 中。我已经按照我在网上可以做得很好的一切,并且没有
我正在研究可以在图像上绘制矩形的东西。它工作得很好,因为 JavaFX 很容易,但我遇到了一个我似乎不理解的小问题。 我一直使用 for (object b : ArrayList) ,但从未发生过这
我对java完全陌生。我花了几个小时寻找这个问题的解决方案,但每个答案都涉及传递参数或使用 void,但在这种情况下我不会这样做。 我有两个 java 文件,一个用于 Room 类,一个用于 Tour
我正在创建一个聊天网站,我正在使用 Strophe.js 和 Strophe.muc.js 插件。单人聊天功能运行良好,但我也不想实现群聊功能,用户可以在其中创建房间并邀请其他用户加入他们的房间。使用
按照教程设置 Room 持久性库时,我在 Android 设备上进行测试时遇到了这个错误。 java.lang.RuntimeException:找不到 PackageName.AppDatabase
我是一名优秀的程序员,十分优秀!