5

I am using next code. This code work fine on desktop version, but on Android device does not. return Gdx.app.getPreferences(PREFS_NAME) always is null. Why? Where I could make mistake?

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();
    }
}
Igor Kostenko
  • 2,754
  • 7
  • 30
  • 57
  • Please include the error stacktrace. I suspect you're reaching `getPrefs` before Gdx.app is initialized (though that should be the similar to the desktop). You should consider adding some `assert` checks that Gdx.app is non-null to distinguish from `getPreferences` returning null, etc. – P.T. Jul 23 '12 at 17:43

2 Answers2

11

Use like this:

   private Preferences preferences;
   protected Preferences getPrefs() {
      if(preferences==null){
         preferences = Gdx.app.getPreferences(PREFS_NAME);
      }
   return preferences;
   }
Nurmuhammad
  • 136
  • 2
  • 8
0

you are not setting the name of the app in .prefs in any way in your code. Add the name just like you added music, vibro...etc

public void setPREFS_NAME() {
    getPrefs().putBoolean("PREFS_NAME", PREFS_NAME);
    getPrefs().flush();
}
Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60
Karani.pranay
  • 191
  • 2
  • 11