0

When user open my Application.

It will call API to my server, and take the json and stored in somewhere, and the json It stored can use anywhere in my application (any Activity, any Fragment, like SharedPreference).

When user close the application, data will clear. Reopen it, It's will calling and storing data again.

What method should I can use? Or any other implementation? Thank you

mikenlanggio
  • 1,122
  • 1
  • 7
  • 27

1 Answers1

0

Extend Application class like this:

    class Global: Application() {
    
        init { instance = this }
    
        companion object {
            private var instance: Global? = null
            lateinit var json: JSONProp
        }

        override fun onCreate() {
            super.onCreate()
            //Fetch Json and store it in jsonProp
        }
    }

Manifest:

<application android:name=".Global" />

You can then use the data anywhere in the app while it's alive like this:

val json = Global.json
Simon
  • 1,657
  • 11
  • 16
  • What difference when implement `Application` vs just Singleton class? – mikenlanggio Aug 18 '20 at 10:28
  • It is convenient for things that should be set up before any of your application logic is executed (I understood you want to fetch the Json as soon as possible on the app start). – Simon Aug 18 '20 at 11:15