4 * StorageManager and KeyValueStorage usage example for Kotlin
5 * Demonstrates working with storage management, key-value storage operations, and data persistence
7class StorageManagerExample {
8 private var sdk: NavigineSdk? = null
9 private var storageManager: StorageManager? = null
10 private var userStorage: KeyValueStorage? = null
11 private var appStorage: KeyValueStorage? = null
12 private var cacheStorage: KeyValueStorage? = null
20 * Initialize SDK and get StorageManager
22 private fun initializeSdk() {
24 // [kotlin_NavigineSdk_getInstance]
26 sdk = NavigineSdk.getInstance()
27 // [kotlin_NavigineSdk_getInstance]
29 // [kotlin_NavigineSdk_setUserHash]
31 sdk?.setUserHash("USER-HASH-HERE")
32 // [kotlin_NavigineSdk_setUserHash]
34 // [kotlin_NavigineSdk_setServer]
35 // Set server URL (optional)
36 sdk?.setServer("https://custom.navigine.com")
37 // [kotlin_NavigineSdk_setServer]
39 // [kotlin_NavigineSdk_getStorageManager]
40 // Get StorageManager for working with storages
41 storageManager = sdk?.getStorageManager()
42 // [kotlin_NavigineSdk_getStorageManager]
44 if (storageManager != null) {
45 println("StorageManager successfully initialized")
47 } catch (e: Exception) {
48 println("Error initializing SDK: ${e.message}")
53 * Setup different storage instances
55 private fun setupStorages() {
56 if (storageManager == null) {
57 println("StorageManager not initialized")
61 // [kotlin_StorageManager_getStorage]
62 // Get or create different storage instances
63 userStorage = storageManager!!.getStorage("user_preferences")
64 appStorage = storageManager!!.getStorage("app_settings")
65 cacheStorage = storageManager!!.getStorage("cache")
66 // [kotlin_StorageManager_getStorage]
68 println("Storage instances created")
72 * Demonstrate StorageManager methods
74 fun demonstrateStorageManagerMethods() {
75 if (storageManager == null) {
76 println("StorageManager not initialized")
80 // [kotlin_StorageManager_getStorageList]
81 // Get list of all existing storages
82 val storageList: List<String> = storageManager!!.getStorageList()
83 println("Existing storages: $storageList")
84 // [kotlin_StorageManager_getStorageList]
86 // [kotlin_StorageManager_getStorage1]
87 // Get or create storage by name
88 val testStorage: KeyValueStorage = storageManager!!.getStorage("test_storage")
89 println("Created test storage")
90 // [kotlin_StorageManager_getStorage1]
92 // Demonstrate storage creation and listing
93 storageManager!!.getStorage("another_storage")
94 val updatedList: List<String> = storageManager!!.getStorageList()
95 println("Updated storage list: $updatedList")
97 // [kotlin_StorageManager_removeStorage]
98 // Remove storage and all its data
99 storageManager!!.removeStorage("test_storage")
100 println("Removed test storage")
101 // [kotlin_StorageManager_removeStorage]
103 val finalList: List<String> = storageManager!!.getStorageList()
104 println("Final storage list: $finalList")
108 * Demonstrate KeyValueStorage methods
110 fun demonstrateKeyValueStorageMethods() {
111 if (userStorage == null) {
112 println("User storage not initialized")
116 println("\n=== KeyValueStorage Methods Demonstration ===")
118 // [kotlin_KeyValueStorage_putString]
119 // Store string values
120 userStorage!!.putString("user_name", "John Doe")
121 userStorage!!.putString("user_email", "john.doe@example.com")
122 println("Stored string values")
123 // [kotlin_KeyValueStorage_putString]
125 // [kotlin_KeyValueStorage_putInt]
126 // Store integer values
127 userStorage!!.putInt("user_age", 25)
128 userStorage!!.putInt("login_count", 42)
129 println("Stored integer values")
130 // [kotlin_KeyValueStorage_putInt]
132 // [kotlin_KeyValueStorage_putLong]
134 userStorage!!.putLong("registration_timestamp", 1640995200000L)
135 userStorage!!.putLong("last_login_timestamp", System.currentTimeMillis())
136 println("Stored long values")
137 // [kotlin_KeyValueStorage_putLong]
139 // [kotlin_KeyValueStorage_putBool]
140 // Store boolean values
141 userStorage!!.putBool("is_premium", true)
142 userStorage!!.putBool("notifications_enabled", false)
143 println("Stored boolean values")
144 // [kotlin_KeyValueStorage_putBool]
146 // [kotlin_KeyValueStorage_putFloat]
147 // Store float values
148 userStorage!!.putFloat("user_rating", 4.5f)
149 userStorage!!.putFloat("temperature", 23.5f)
150 println("Stored float values")
151 // [kotlin_KeyValueStorage_putFloat]
153 // [kotlin_KeyValueStorage_putDouble]
154 // Store double values
155 userStorage!!.putDouble("user_location_lat", 55.7558)
156 userStorage!!.putDouble("user_location_lng", 37.6176)
157 println("Stored double values")
158 // [kotlin_KeyValueStorage_putDouble]
160 // [kotlin_KeyValueStorage_contains]
161 // Check if keys exist
162 val hasUserName: Boolean = userStorage!!.contains("user_name")
163 val hasNonExistent: Boolean = userStorage!!.contains("non_existent_key")
164 println("Contains 'user_name': $hasUserName")
165 println("Contains 'non_existent_key': $hasNonExistent")
166 // [kotlin_KeyValueStorage_contains]
168 // [kotlin_KeyValueStorage_getKeys]
169 // Get all stored keys
170 val allKeys: List<String> = userStorage!!.getKeys()
171 println("All stored keys: $allKeys")
172 // [kotlin_KeyValueStorage_getKeys]
174 // [kotlin_KeyValueStorage_getString]
175 // Retrieve string values with defaults
176 val userName: String = userStorage!!.getString("user_name", "Unknown")
177 val userEmail: String = userStorage!!.getString("user_email", "")
178 val nonExistent: String = userStorage!!.getString("non_existent_key", "default_value")
179 println("User name: $userName")
180 println("User email: $userEmail")
181 println("Non-existent key: $nonExistent")
182 // [kotlin_KeyValueStorage_getString]
184 // [kotlin_KeyValueStorage_getInt]
185 // Retrieve integer values with defaults
186 val userAge: Int = userStorage!!.getInt("user_age", 0)
187 val loginCount: Int = userStorage!!.getInt("login_count", 0)
188 val nonExistentInt: Int = userStorage!!.getInt("non_existent_int", -1)
189 println("User age: $userAge")
190 println("Login count: $loginCount")
191 println("Non-existent int: $nonExistentInt")
192 // [kotlin_KeyValueStorage_getInt]
194 // [kotlin_KeyValueStorage_getLong]
195 // Retrieve long values with defaults
196 val regTimestamp: Long = userStorage!!.getLong("registration_timestamp", 0)
197 val lastLogin: Long = userStorage!!.getLong("last_login_timestamp", 0)
198 val nonExistentLong: Long = userStorage!!.getLong("non_existent_long", -1)
199 println("Registration timestamp: $regTimestamp")
200 println("Last login timestamp: $lastLogin")
201 println("Non-existent long: $nonExistentLong")
202 // [kotlin_KeyValueStorage_getLong]
204 // [kotlin_KeyValueStorage_getBool]
205 // Retrieve boolean values with defaults
206 val isPremium: Boolean = userStorage!!.getBool("is_premium", false)
207 val notificationsEnabled: Boolean = userStorage!!.getBool("notifications_enabled", true)
208 val nonExistentBool: Boolean = userStorage!!.getBool("non_existent_bool", false)
209 println("Is premium: $isPremium")
210 println("Notifications enabled: $notificationsEnabled")
211 println("Non-existent bool: $nonExistentBool")
212 // [kotlin_KeyValueStorage_getBool]
214 // [kotlin_KeyValueStorage_getFloat]
215 // Retrieve float values with defaults
216 val userRating: Float = userStorage!!.getFloat("user_rating", 0.0f)
217 val temperature: Float = userStorage!!.getFloat("temperature", 0.0f)
218 val nonExistentFloat: Float = userStorage!!.getFloat("non_existent_float", -1.0f)
219 println("User rating: $userRating")
220 println("Temperature: $temperature")
221 println("Non-existent float: $nonExistentFloat")
222 // [kotlin_KeyValueStorage_getFloat]
224 // [kotlin_KeyValueStorage_getDouble]
225 // Retrieve double values with defaults
226 val userLat: Double = userStorage!!.getDouble("user_location_lat", 0.0)
227 val userLng: Double = userStorage!!.getDouble("user_location_lng", 0.0)
228 val nonExistentDouble: Double = userStorage!!.getDouble("non_existent_double", -1.0)
229 println("User location lat: $userLat")
230 println("User location lng: $userLng")
231 println("Non-existent double: $nonExistentDouble")
232 // [kotlin_KeyValueStorage_getDouble]
234 // [kotlin_KeyValueStorage_remove]
235 // Remove specific keys
236 userStorage!!.remove("user_age")
237 userStorage!!.remove("non_existent_key") // No-op
238 println("Removed 'user_age' key")
239 // [kotlin_KeyValueStorage_remove]
242 val stillHasAge: Boolean = userStorage!!.contains("user_age")
243 println("Still contains 'user_age': $stillHasAge")
245 // [kotlin_KeyValueStorage_clear]
247 userStorage!!.clear()
248 println("Cleared all data from user storage")
249 // [kotlin_KeyValueStorage_clear]
252 val keysAfterClear: List<String> = userStorage!!.getKeys()
253 println("Keys after clear: $keysAfterClear")
257 * Demonstrate multiple storages
259 fun demonstrateMultipleStorages() {
260 if (userStorage == null || appStorage == null || cacheStorage == null) {
261 println("Storages not initialized")
265 println("\n=== Multiple Storages Demonstration ===")
267 // Store different data in different storages
268 userStorage!!.putString("name", "John Doe")
269 userStorage!!.putInt("age", 25)
270 userStorage!!.putBool("is_premium", true)
272 appStorage!!.putString("theme", "dark")
273 appStorage!!.putInt("api_version", 2)
274 appStorage!!.putBool("debug_mode", false)
276 cacheStorage!!.putLong("last_update", System.currentTimeMillis())
277 cacheStorage!!.putString("api_token", "abc123")
278 cacheStorage!!.putDouble("cached_rating", 4.2)
280 // Retrieve data from different storages
281 println("User storage data:")
282 demonstrateStorageData(userStorage!!)
284 println("\nApp storage data:")
285 demonstrateStorageData(appStorage!!)
287 println("\nCache storage data:")
288 demonstrateStorageData(cacheStorage!!)
292 * Demonstrate storage data
294 private fun demonstrateStorageData(storage: KeyValueStorage) {
295 val keys: List<String> = storage.getKeys()
297 if (storage.contains(key)) {
298 // Try to get value as string first
299 val stringValue: String = storage.getString(key, "")
300 if (stringValue.isNotEmpty()) {
301 println(" $key: $stringValue (string)")
306 val intValue: Int = storage.getInt(key, -999999)
307 if (intValue != -999999) {
308 println(" $key: $intValue (int)")
313 val longValue: Long = storage.getLong(key, -999999)
314 if (longValue != -999999) {
315 println(" $key: $longValue (long)")
320 val boolValue: Boolean = storage.getBool(key, false)
321 if (storage.contains(key)) {
322 println(" $key: $boolValue (bool)")
327 val floatValue: Float = storage.getFloat(key, -999999.0f)
328 if (floatValue != -999999.0f) {
329 println(" $key: $floatValue (float)")
334 val doubleValue: Double = storage.getDouble(key, -999999.0)
335 if (doubleValue != -999999.0) {
336 println(" $key: $doubleValue (double)")
343 * Demonstrate storage analytics
345 fun demonstrateStorageAnalytics() {
346 if (storageManager == null) {
347 println("StorageManager not initialized")
351 println("\n=== Storage Analytics ===")
353 // Analyze all storages
354 val allStorages: List<String> = storageManager!!.getStorageList()
355 println("Total storages: ${allStorages.size}")
357 for (storageName in allStorages) {
358 val storage: KeyValueStorage = storageManager!!.getStorage(storageName)
359 val keys: List<String> = storage.getKeys()
360 println("Storage '$storageName' contains ${keys.size} items")
362 // Analyze data types
371 // Count by trying to get each type
372 val stringValue: String = storage.getString(key, "")
373 if (stringValue.isNotEmpty()) {
378 val intValue: Int = storage.getInt(key, -999999)
379 if (intValue != -999999) {
384 val longValue: Long = storage.getLong(key, -999999)
385 if (longValue != -999999) {
390 val boolValue: Boolean = storage.getBool(key, false)
391 if (storage.contains(key)) {
396 val floatValue: Float = storage.getFloat(key, -999999.0f)
397 if (floatValue != -999999.0f) {
402 val doubleValue: Double = storage.getDouble(key, -999999.0)
403 if (doubleValue != -999999.0) {
408 println(" - Strings: $stringCount")
409 println(" - Integers: $intCount")
410 println(" - Longs: $longCount")
411 println(" - Booleans: $boolCount")
412 println(" - Floats: $floatCount")
413 println(" - Doubles: $doubleCount")
418 * Demonstrate data migration
420 fun demonstrateDataMigration() {
421 if (storageManager == null) {
422 println("StorageManager not initialized")
426 println("\n=== Data Migration Demonstration ===")
428 // Create old and new storages
429 val oldStorage: KeyValueStorage = storageManager!!.getStorage("old_storage")
430 val newStorage: KeyValueStorage = storageManager!!.getStorage("new_storage")
432 // Populate old storage with data
433 oldStorage.putString("name", "John Doe")
434 oldStorage.putInt("age", 25)
435 oldStorage.putBool("is_premium", true)
436 oldStorage.putDouble("rating", 4.5)
438 println("Old storage before migration:")
439 demonstrateStorageData(oldStorage)
441 // Migrate data from old to new storage
442 val keys: List<String> = oldStorage.getKeys()
444 // Migrate string data
445 val stringValue: String = oldStorage.getString(key, "")
446 if (stringValue.isNotEmpty()) {
447 newStorage.putString(key, stringValue)
451 // Migrate integer data
452 val intValue: Int = oldStorage.getInt(key, -999999)
453 if (intValue != -999999) {
454 newStorage.putInt(key, intValue)
459 val longValue: Long = oldStorage.getLong(key, -999999)
460 if (longValue != -999999) {
461 newStorage.putLong(key, longValue)
465 // Migrate boolean data
466 val boolValue: Boolean = oldStorage.getBool(key, false)
467 if (oldStorage.contains(key)) {
468 newStorage.putBool(key, boolValue)
472 // Migrate float data
473 val floatValue: Float = oldStorage.getFloat(key, -999999.0f)
474 if (floatValue != -999999.0f) {
475 newStorage.putFloat(key, floatValue)
479 // Migrate double data
480 val doubleValue: Double = oldStorage.getDouble(key, -999999.0)
481 if (doubleValue != -999999.0) {
482 newStorage.putDouble(key, doubleValue)
486 println("\nNew storage after migration:")
487 demonstrateStorageData(newStorage)
489 // Remove old storage
490 storageManager!!.removeStorage("old_storage")
491 println("\nRemoved old storage")
494 val finalStorages: List<String> = storageManager!!.getStorageList()
495 println("Final storage list: $finalStorages")
499 * Demonstrate storage cleanup
501 fun demonstrateStorageCleanup() {
502 if (storageManager == null) {
503 println("StorageManager not initialized")
507 println("\n=== Storage Cleanup Demonstration ===")
509 // Create some temporary storages
510 storageManager!!.getStorage("temp_cache_1")
511 storageManager!!.getStorage("temp_cache_2")
512 storageManager!!.getStorage("permanent_storage")
514 val beforeCleanup: List<String> = storageManager!!.getStorageList()
515 println("Storages before cleanup: $beforeCleanup")
517 // Clean up temporary storages
518 val storages: List<String> = storageManager!!.getStorageList()
519 for (storageName in storages) {
520 if (storageName.startsWith("temp_")) {
521 storageManager!!.removeStorage(storageName)
522 println("Removed temporary storage: $storageName")
526 val afterCleanup: List<String> = storageManager!!.getStorageList()
527 println("Storages after cleanup: $afterCleanup")
531 * Run all demonstrations
533 fun runAllDemonstrations() {
534 println("=== StorageManager and KeyValueStorage Examples ===\n")
536 demonstrateStorageManagerMethods()
537 demonstrateKeyValueStorageMethods()
538 demonstrateMultipleStorages()
539 demonstrateStorageAnalytics()
540 demonstrateDataMigration()
541 demonstrateStorageCleanup()
543 println("\n=== All demonstrations completed ===")
550 if (storageManager != null) {
551 // Remove test storages
552 val storages: List<String> = storageManager!!.getStorageList()
553 for (storageName in storages) {
554 if (storageName.startsWith("test_") ||
555 storageName.startsWith("temp_") ||
556 storageName.startsWith("old_") ||
557 storageName.startsWith("new_")) {
558 storageManager!!.removeStorage(storageName)
566 * Main function to run the example
569 val example = StorageManagerExample()
571 // Run all demonstrations
572 example.runAllDemonstrations()
577 println("Example completed successfully!")