bugraarslan bugraarslan - 5 months ago 9
Android Question

Android Studio - Can't Read preferenceSettings

I am trying to save user's language using SharedPreference. MainActivity is my main activity and SettingsActivity is where I ask and save user's language.

Saving:

private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
public void save(String lg){
preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("language", lg);
preferenceEditor.commit();
finish();
}


Reading:

preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
String LanguageS = preferenceSettings.getString("language", "0");


with this code, I can successfully save and read from same activity(SettingsActivity) but when I return to my main activity, I can't read.

I am using this code to read from my main activity but it always returns "0".

private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static String Lang = "0";

preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
Lang = preferenceSettings.getString("language", "0");


What am I doing wrong? I am controlling these lines for almost 1 hour but couldn't find any mistakes.

Answer

Instead of using getPreferences(int mode), you should use the getSharedPreferences(String name, int mode)

If you read the java doc on the getPreferences(int mode) it says:

Retrieve a {@link SharedPreferences} object for accessing preferences
that are private to this activity. 

This simply calls the underlying
{@link #getSharedPreferences(String, int)} method by 
passing in this activity's class name as the preferences name. @param
mode Operating mode.  

Use {@link #MODE_PRIVATE} for the default
operation, {@link #MODE_WORLD_READABLE} and {@link
MODE_WORLD_WRITEABLE} to control permissions.
@return Returns the single SharedPreferences instance that can be used
to retrieve and modify the preference values.
Comments