views:

64

answers:

2

Hi,

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( , MODE_WORLD_WRITEABLE); HashMap map = (HashMap) 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

A: 

How do I use/edit preferences created by one app in another app.

If they are both your own apps, use android:sharedUserId, so they both run as the same user and have direct access to each others files, without file permission changes.

If I figure out how to create MODE_WORLD_WRITEABLE preferences using PreferenceActivity that will solve the problem.

And create a security hole in your app.

CommonsWare
I guess I am missing something as its not working.sharedUserId: com.artoo.shared (Do I need to set a sharedLabel?)1st app: com.artoo / com.artoo_preferences2nd app: com.artoo.customers / com.artoo.customers_preferencesI am unable to access the 1st preference in the 2nd app with MODE_PRIVATE. Please help
Sameer Segal
@Sameer Segal: I have not used the technique personally, so I do not know what problems you might be experiencing.
CommonsWare
I am running the apps on the emulator -- could it be that they are getting signed by different keys?
Sameer Segal
@Sameer Segal: If you are doing debug builds on the same PC, they will have the same signing key. If you are doing debug builds on different PCs, by default, they will have different signing keys. And if you are doing production builds, you are signing them yourself, so you should know what keys you're using. :-)
CommonsWare
+1  A: 

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