问题描述:

I'm trying to save some keys with SharedPreferences on the first APP, then when initialized the second APP, load them.

It works on the emulator but not on a device (Android 4.0.3)

This is my code on the first APP:

private SharedPreferences gameSaved;

private SharedPreferences.Editor editor;

gameSaved = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

int value = 10;

editor = gameSaved.edit();

editor.putInt("value_0", value);

editor.commit();

Then on the second APP I get the key value like this:

try{

con = getApplicationContext().createPackageContext("com.example.firstapp", 0);

} catch (NameNotFoundException e) {

}

SharedPreferences pref = con.getSharedPreferences(PREFS_NAME, Context.CONTEXT_IGNORE_SECURITY);

int value = pref.getInt("value_0", -1);

On the manifest both APPs share this line:

android:sharedUserId="com.example.shared"

I've check that SharedPreferences file is correctly created and located.

The most strange thing is it works perfectly on the emulator.

Please help, I'm running out of ideas.

网友答案:

I finally could solve it but I don't have any technical explanation for it.

Previously I had on both APPs the same file name for it:

SharedPreferences pref = con.getSharedPreferences(FILE_NAME, Context.CONTEXT_IGNORE_SECURITY);

It doesn't have much sense because those files are stored/saved in the different APP's data folder but if they share the same SharedPreferences file name then it won't work (at least for me).

相关阅读:
Top