1
\$\begingroup\$

I'm using the code in this tutorial (Full LibGDX game tutorial). The code to save the preferences works fine on Desktop but not on Android. Here's how I access and save my preferences:

public class AppPreferences {
private static final String PREF_MUSIC_VOLUME = "volume";
private static final String PREF_MUSIC_ENABLED = "music.enabled";
private static final String PREF_SOUND_ENABLED = "sound.enabled";
private static final String PREF_SOUND_VOL = "sound";
private static final String PREFS_NAME = "b2dtut";

protected Preferences getPrefs() {
    return Gdx.app.getPreferences(PREFS_NAME);
}

public boolean isSoundEffectsEnabled() {
    return getPrefs().getBoolean(PREF_SOUND_ENABLED, true);
}

public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
    getPrefs().putBoolean(PREF_SOUND_ENABLED, soundEffectsEnabled);
    getPrefs().flush();
}

public boolean isMusicEnabled() {
    return getPrefs().getBoolean(PREF_MUSIC_ENABLED, true);
}

public void setMusicEnabled(boolean musicEnabled) {
    getPrefs().putBoolean(PREF_MUSIC_ENABLED, musicEnabled);
    getPrefs().flush();
}

public float getMusicVolume() {
    return getPrefs().getFloat(PREF_MUSIC_VOLUME, 0.5f);
}

public void setMusicVolume(float volume) {
    getPrefs().putFloat(PREF_MUSIC_VOLUME, volume);
    getPrefs().flush();
}

public float getSoundVolume() {
    return getPrefs().getFloat(PREF_SOUND_VOL, 0.5f);
}

public void setSoundVolume(float volume) {
    getPrefs().putFloat(PREF_SOUND_VOL, volume);
    getPrefs().flush();
}
}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

On Android, for some reason you have to store the reference to the Preferences object instead of accessing it using Gdx.app.getPreferences(PREFS_NAME). It probably has to do with how Android's built-in preferences work and how getPreferences interracts with it but I am unsure of the exact reason why. To solve this simply make this change:

private Preferences preferences;

protected Preferences getPrefs() {
    if (preferences == null)
        preferences = Gdx.app.getPreferences(PREFS_NAME);
    return preferences;
}
\$\endgroup\$
1
  • \$\begingroup\$ In fact, it is fair for desktop apps too \$\endgroup\$
    – Nolesh
    Aug 15, 2018 at 5:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .