For my Android project, I need global singleton Cache object to access data about a user through the app.
A problem occurs when an app goes into the background and after some time of using other apps I try to open app variables in Cache objects are null. Everything is okay when I kill the app and open it again. I'm using dependency injection to access Cache object. Why doesn't app start again if that happened? Is there some annotation to keep cache variable even in low memory conditions?
This is my Cache class
class Cache {
var categories : Array<BaseResponse.Category>? = null
var user : BaseResponse.User? = null
var options : BaseResponse.OptionsMap? = null
var order: MenuOrderDataModel? = null
}
This is Storage module for DI
@Module class StorageModule {
@Singleton @Provides fun getSharedPrefs(context: Context): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(context)
}
@Singleton @Provides fun getCache() : Cache = Cache()
}
I inject object @Inject lateinit var cache: Cache
and then populate with user data in splash screen.
Edit - added code snippets from Application and launch activity
class MyApp : Application() {
val component: ApplicationComponent by lazy {
DaggerApplicationComponent
.builder()
.appModule(AppModule(this))
.build()
}
companion object {
@JvmStatic lateinit var myapp: MyApp
}
override fun onCreate() {
super.onCreate()
myapp= this
Fabric.with(this, Crashlytics())
}
}
Splash activity:
class SplashActivity : AppCompatActivity(), View.OnClickListener {
@Inject lateinit var viewModel : ISplashViewModel
private lateinit var disposable : Disposable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
MyApp.myapp.component.inject(this)
}