apsun / RemotePreferences

A drop-in solution for inter-app access to SharedPreferences.
MIT License
138 stars 32 forks source link

Variable preference name? #21

Closed Dr-TSNG closed 3 years ago

Dr-TSNG commented 3 years ago

My app has sharedpreferences of variable count and names, how can I add them all to MyPreferenceProvider? Since super(...) must be on the first line of the constructor, I cannot create a variable string array as parameter.

apsun commented 3 years ago

Unfortunately, RemotePreferences does not support this. The main reason is that RemotePreferences aims to be fully API compatible with SharedPreferences, and SharedPreferences has OnSharedPreferenceChangeListener which can't be implemented through the ContentProvider API without knowing upfront the complete set of preferences to listen for.

If you want a 2-level deep preference tree, I would recommend encoding it in the key instead (like, change getSharedPreferences("foo").getString("bar") to getSharedPreferences("all").getString(foo:bar") or something like that).

Dr-TSNG commented 3 years ago

Oh, that's so bad. Since my app has complex preference structure, encoding in the key seems so troublesome. In fact, I just want package "android" to read the preferences from my Xposed module (no need for write), without using "new XSharedPreferences" from API 93. Is there any solution?

apsun commented 3 years ago

I don't see why it's so hard? Just define a function to transform the file name and key into a single string, and use that everywhere. Alternatively, use the filename as the key, and store the value as a JSON object encoded into a string (which sounds appropriate anyways if you truly have "complex preference structure").

It's unlikely that RemotePreferences will ever support variable file names, as it adds a lot of complexity on our end, or breaking backwards compatibility, or both, for little benefit (imo, unless you can convince me otherwise). Sorry.

Dr-TSNG commented 3 years ago

Yes you are right, storing the values as json is a perfect solution, thanks.

Android1500 commented 3 years ago

Yes you are right, storing the values as json is a perfect solution, thanks.

You can use target sdk 23 and and use MODE_WORDLD_READABLE