3

I have multiple applications that share certain data through preferences. Each app sets its preferences through a PreferenceActitivity (from xml). Two questions:

How do I use/edit preferences created by one app in another app. If I figure out how to create MODE_WORLD_WRITEABLE preferences using PreferenceActivity that will solve the problem.

 SharedPreferences prefs = getSharedPreferences(
          <String referring to another package´s prefs>, MODE_WORLD_WRITEABLE);
        HashMap<String, String> map = (HashMap<String, String>) prefs
          .getAll();


        String str = map.toString();
        tv.setText(str);

Above code returns {}

  • Second, how do I use addPreferencesFromIntent(i) -- I am getting a NullPointerException even though the intent is not Null.

Thanks for the help in advance.

Best, Sameer

Robin
  • 10,011
  • 5
  • 49
  • 75
Sameer Segal
  • 21,813
  • 7
  • 42
  • 56

1 Answers1

6

To access preferences from another app in a secure way set the same android:sharedUserId in the Manifest. This will allow you to access preferences & files in MODE_PRIVATE (or secure) manner.

After much time spent, we realized this alone will not work and one needs to create a package context of the first app to access files in the second app:

try {
            Context c = createPackageContext(com.app.first, MODE_PRIVATE);
            SharedPreferences prefs = c.getSharedPreferences(
                    "com.app.first_preferences", MODE_PRIVATE);

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

A big thank you to @CommonsWare and Karthik Shanmugam for their help!

Sameer Segal
  • 21,813
  • 7
  • 42
  • 56
  • But you cannot add sharedUserId if the apps are already live... It messes a lot of things up. Just my 2 cents. – Anthony Graglia Jan 30 '11 at 18:55
  • The downside of this solution is that second application must assume that the first application is installed. See http://stackoverflow.com/q/11803585/722603 – ef2011 Aug 03 '12 at 23:07