How to Keep Lateinit Global Variables in Android Apps

Asked 2 years ago, Updated 2 years ago, 102 views

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)

android kotlin

2022-09-30 13:54

1 Answers

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.

  • Use Intent to exchange data between activities
    • This depends on the environment, but the maximum size is said to be about 1MB.
  • Persistent using local database, etc. and restoring per Activity
  • Initialize with null instead of lateinit and always do null check
  • This depends on the environment, but the maximum size is said to be about 1MB.

It's an old article, so it's not mentioned, but you can also use the following interface:

  • Using ViewModelStoreOwner in the Allocation Scope


2022-09-30 13:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.