How to save the game using LibGDX settings on Android devices?

I am using the following code. This code works fine on the desktop version, but not on an Android device. return Gdx.app.getPreferences (PREFS_NAME) is always null. What for? Where could I be wrong?

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;

public class BeatlesPreferences {
    // constants
    private static final String PREF_VIBRO = "vibro";
    private static final String PREF_MUSIC_ENABLED = "musicenabled";
    private static final String PREF_SOUND_ENABLED = "soundenabled";
    private static final String PREFS_NAME = "my_app";

    public BeatlesPreferences() {
    }

    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 boolean isVibroEnabled() {
        return getPrefs().getBoolean(PREF_VIBRO, true);
    }

    public void setVibroEnabled(boolean vibro) {
        getPrefs().putBoolean(PREF_VIBRO, vibro);
        getPrefs().flush();
    }
}
+5
source share
2 answers

Use this:

   private Preferences preferences;
   protected Preferences getPrefs() {
      if(preferences==null){
         preferences = Gdx.app.getPreferences(PREFS_NAME);
      }
   return preferences;
   }
+11
source

you do not specify the application name in .prefs in any way in your code. Add a name just like you added music, vibro ... etc.

public void setPREFS_NAME() {
    getPrefs().putBoolean("PREFS_NAME", PREFS_NAME);
    getPrefs().flush();
}
0
source

All Articles