I use kotlin to develop Android apps.
The app I'm developing is like a news app, and there's a favorite saving function called clip.
When the application starts, it retrieves a list of clips stored in DB and keeps them in the global variable of lateinit, but some users are experiencing a crash where lateinit is not initialized.
Unable to start activity ComponentInfo {xxx.xxx.xxx/xxx.xxx.xxx.activity.XXXActivity}: kotlin.UnitializedPropertyAccessException:lateinitproperty clipList has not been initialized
The clipList
was obtained when the application was started, and the application was not available until it was surely obtained, so there should be no omission of initialization.
We believe that the singleton class holding the global variable has been discarded due to memory overload.
The specific implementation is listed below, but I thought it would not be discarded because it inherits the application class. How is it right to keep these global variables?
Please let me know.
global variable retention class
class MyApp:Application(){
// ClipAdvice is a self-made list of articles
lateinit varclipList —ArrayList<ClipAdvice>
override fun onCreate() {
super.onCreate()
}
US>companion object {
valsharedInstance:MyApp by lazy {
MyApp()
}
}
}
Code accessing global variables
MyApp.sharedInstance.clipList.add(0,clip)
In Android, data held in the application class may disappear.
For more information, please refer to the article below.
http://www.developerphil.com/dont-store-data-in-the-application-object/
As mentioned in the article, there are several ways to retain data between Activity.
It's an old article, so it's not mentioned, but you can also use the following interface:
© 2024 OneMinuteCode. All rights reserved.