How can data be saved outside a fragment?
sobes.tech AI
Answer from AI
There are several ways to store data outside a fragment:
-
ViewModel: Ideal for storing UI-related data in a lifecycle-aware manner. Survives configuration changes.class MyViewModel : ViewModel() { var data: String = "" } -
Activity: Fragments can interact with the container activity (e.g., via interface or directly), where data can be stored.
// In Activity var sharedData: String = "" // In Fragment (activity as? MyActivity)?.sharedData = "Saved from fragment" -
Shared Preferences: A simple way to store primitive data (small amounts).
// In Fragment val sharedPref = activity?.getSharedPreferences("my_prefs", Context.MODE_PRIVATE) ?: return with(sharedPref.edit()) { putString("saved_string", "My data") apply() // Or commit() for synchronous write } -
SQLite Database: For structured data and more complex queries.
-- Example SQL CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT); -
Room Persistence Library: An abstraction over SQLite that simplifies database work.
// Example Room Entity @Entity data class User( @PrimaryKey val id: Int, val name: String ) -
DataStore: A more modern alternative to Shared Preferences, allowing asynchronous and safe data storage.
// Example DataStore Prefs val EXAMPLE_COUNTER = intPreferencesKey("example_counter") // In Fragment context?.dataStore?.edit { settings -> val currentCounter = settings[EXAMPLE_COUNTER] ?: 0 settings[EXAMPLE_COUNTER] = currentCounter + 1 } -
Internal/External Storage: For storing files.
// Writing to a file val filename = "my_data.txt" val fileContents = "Hello, world!" context?.openFileOutput(filename, Context.MODE_PRIVATE)?.use { it.write(fileContents.toByteArray()) } -
Singleton: A global instance of a class for storing data, accessible from anywhere in the app. Use cautiously due to potential testing issues and memory leaks.
object DataManager { var sharedData: String = "" } -
Application Class: A class extending
Applicationthat is global for the entire app and can store data.class MyApp : Application() { var globalData: String = "" }