A
A
Alexander Sinitsyn2016-10-30 23:01:13
Android
Alexander Sinitsyn, 2016-10-30 23:01:13

How to organize the storage of settings?

Probably hackneyed, but I can not find a complete answer. There is a service, there is an activation of the settings. Settings in SharedPreferences. How to organize storage, access in all classes, change notification.
I wanted to make a helper class with static fields and methods, but SharedPreferences requires a Context, it turns out that the class must be initialized by some method with the transfer of this context.
Who does what?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2016-10-30
@GavriKos

Overload the Application class, there you can get the context and initialize your settings storage class. You overload application with a singleton, and make a getter for settings in it. Everything - you can work from any class.

Y
Yuri, 2016-10-31
@YuryBorodkin

so we do.
There are two ways, fast and correct:
fast - in Application onCreate() we take the context, put it into a static variable, and in the helper class, static methods use this context. the solution is bad - conceptually we violate the OOP, SOLID. In practice, it is bad to test such code, because a) only PowerMock takes static methods and b) our classes will have unrestricted access there, i.e. the problem of global variables at its finest.
correct: Naturally we do SharedPreferenceFactory and further according to classical java canons. Or, if you remember that we live in 2016 - through DI.
And yes, writing code quickly - it hurts to maintain, why chase imaginary speed - xs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question