generated from me/template-mit
51 lines
1.5 KiB
Kotlin
51 lines
1.5 KiB
Kotlin
package com.hyperling.weather
|
|
|
|
import android.content.Context
|
|
|
|
/**
|
|
* SharedPreferences-based local storage manager for location entries (Android).
|
|
*/
|
|
class AndroidStorageBackend(private val context: Context) : StorageBackend {
|
|
|
|
private companion object {
|
|
const val PREFS_NAME = "nomadic_weather_prefs"
|
|
const val KEY_LOCATIONS = "locations_json"
|
|
}
|
|
|
|
private val prefs by lazy {
|
|
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
|
}
|
|
|
|
override fun load(): List<LocationEntry> {
|
|
val jsonStr = prefs.getString(KEY_LOCATIONS, null) ?: return emptyList()
|
|
if (jsonStr.isEmpty()) return emptyList()
|
|
return try {
|
|
LocationSerializer.jsonToLocations(jsonStr)
|
|
} catch (e: Exception) {
|
|
emptyList()
|
|
}
|
|
}
|
|
|
|
override fun save(locations: List<LocationEntry>) {
|
|
prefs.edit().putString(KEY_LOCATIONS, LocationSerializer.locationsToJson(locations)).apply()
|
|
}
|
|
|
|
override fun saveOne(location: LocationEntry) {
|
|
val existing = load().toMutableList()
|
|
val idx = existing.indexOfFirst { it == location }
|
|
if (idx >= 0) existing[idx] = location
|
|
else {
|
|
if (existing.size >= 8) existing.removeAt(0)
|
|
existing.add(location)
|
|
}
|
|
save(existing)
|
|
}
|
|
|
|
override fun delete(id: Long) {
|
|
save(load().filter { it.id != id })
|
|
}
|
|
}
|
|
|
|
actual fun LocationStorage.getStorage(): StorageBackend =
|
|
throw UnsupportedOperationException("getStorage requires AndroidContext - this is a desktop build")
|