Junior
How can we temporarily store an object in Android?
sobes.tech AI
Answer from AI
Temporarily saving an object in Android can be done in several ways, depending on its lifespan and the need for access after the component is finished:
- View State: Objects related to a View can be saved in its state, which is restored when the View is recreated (for example, during screen rotation).
onSaveInstanceState()andonRestoreInstanceState()are used. ViewModel: The best way to save data related to UI that should survive configuration changes of Activity/Fragment (for example, screen rotations).ViewModelexists until the ViewModelStoreOwner is destroyed.// In Activity/Fragment val viewModel = ViewModelProvider(this).get(MyViewModel::class.java) // In ViewModel class MyViewModel : ViewModel() { var myObject: MyData? = null }onRetainCustomNonConfigurationInstance()(deprecated): A method in Activity to save arbitrary objects that will survive configuration changes.getLastNonConfigurationInstance()is used to retrieve the object. Deprecated in favor ofViewModel.// In Activity override fun onRetainCustomNonConfigurationInstance(): Any? { return myObjectToRetain } // To get the object val retainedObject = lastCustomNonConfigurationInstance as? MyDataApplicationclass: For objects that should live throughout the entire application lifecycle. Use with caution to avoid storing too much data.- Temporary files: For larger objects that do not fit directly into memory or require short-term storage on disk.
| Method | Lifespan | Usage |
|---|---|---|
| View State | View life + recreation state | Small data related to View |
| ViewModel | Activity/Fragment life | UI data surviving configuration changes |
| onRetainCustomNonConfigurationInstance() | Activity life + recreation state | Arbitrary objects (deprecated) |
| Application class | Application life | Global objects |
| Temporary files | Developer-defined | Large objects, temporary storage |