Reputation: 53
I have an android application that has uses few serializable classes (I can store and load them in JSON format using Google Gson library and it works like a charm).
Now I want to provide way for user to edit those objects in fashion similar to PreferenceActivity - they contain few strings, ints and doubles and PreferenceScreen just seems ideal for editing them.
Is there a way to 'abuse' PreferenceActivity to provide UI for editing my objects without actually storing data in shared preferences?
For example - if there was some callback to override that is called just before saving data, I could extract data, assemble my object and somehow prevent Android from messing with preferences?
Upvotes: 2
Views: 494
Reputation: 10308
SharedPreferences
is an interface, so you should be able to provide your own implementation that stores data however you like. But the PreferenceManager
used by PreferenceFragment
only has a setter that takes a file name, not a custom implementation of SharedPreferences
.
I looked into the source and found a roundabout way to use your own implementation. PreferenceFragment
uses its hosting Activity
as the Context
for constructing a PreferenceManager
. PreferenceManager
subsequently calls Context#getSharedPreferences(String, int)
to get the SharedPreferences
that it will use. Therefore, you can override getSharedPreferences
in the activity hosting your PreferenceFragment
and return your custom implementation. Implementing SharedPreferences
could be rather complicated since you'll also have to implement SharedPreferences.Editor
, but it's doable. And if there's any chance of your overridden getSharedPreferences
being used anywhere else, you should document that it uses a different backing store.
In the Android O preview, there's a new interface called PreferenceDataStore
and a new setter in PreferenceManager
that takes an instance of that interface. PreferenceDataStore
looks much simpler to implement than SharedPreferences
. But as I write this, most retailers are still selling L and M devices, so who knows when we'll see O.
Upvotes: 2
Reputation: 20140
First I would think if I really want to present objects editing with preferences UI since it might confuse a user.
If you still decide to go this way you can achieve it with:
PreferenceManager
and use reflection to replace private field in PreferenceActivity
The first one is straight forward and rather simple to implement, might have some performance implications. The second one might get tricky and probably requires more code to write.
I would still advice to revise decision to "re-use" PreferenceActivity
for such case.
Upvotes: 1