7

Does anyone know if android supports sharing the same sharedpreference across multiple Android Modules compiled in one project?

i have two shared preferences and currently when i try to access some data from a shared prefence outside of the current module, it doesnt work and creates a new sharedPrefence instead

example

Module one:

 mSharedPreferences = context.getSharedPreferences(
                "pref", Context.MODE_PRIVATE);

Module Two:

 mSharedPreferences = context.getSharedPreferences(
                "pref", Context.MODE_PRIVATE);

It creates two preference file instead of one where both modules can share the data

Jono
  • 17,341
  • 48
  • 135
  • 217

2 Answers2

4

You can create a common :core module and add all your dependencies in that module.

Implement :core module in all your other modules.

Place you PrefHelpers class in :core module to access them from any module or you could configure sharedpreference using common package name can be obtained using BuildConfig.APPLICATION_ID.

 mSharedPreferences = context.getSharedPreferences(
                "pref", Context.MODE_PRIVATE);

can be replaced with

mSharedPreferences = context.getSharedPreferences(
                BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);

You can use the mode as Context.MODE_PRIVATE itself.

Make sure your BuildConfig is from your :core module.

If it resolves your issue comment back.

  • and this `:core` module will dependent on `:app` module to get the reference to app's context. right? – Yogesh Seralia Jul 08 '19 at 04:56
  • Did you manage to work with this solution? the Context is different between the two modules so I'm not sure `context.getSharedPreferences` will lead to the same location – Tomer Petel Dec 09 '21 at 13:25
3

You can do it by setting Context.MODE_WORLD_READABLE (deprecated in API 17), but its highly not recommended. I would use ContentProvider, BroadcastReceiver, or Service instead to pass data between two modules, as it is suggested in the docs by the link above.

artman
  • 632
  • 2
  • 7
  • 16