Search code examples
libgdxpreferences

Libgdx: Different profiles of Preferences


I've searched around and haven't found anything related to what I'm trying to achieve.

To explain as simple as possible. My app stores various number of values, acting as settings for the user basically. Now what I want is for the user to have the ability to switch between different preference files. Like different profiles. So on a click of a button all instances of Preferences through the app will start reading a different file with different values, for example:

main.preferences = Gdx.app.getPreferences("prefs_2");

where the first profile would be "prefs_1" instead which is loaded by default when the app starts. I don't know if just changing the preference file like shown above would work at all. But I hope it gives an idea of how I'm thinking.

And when clicking that button to change preference file, the app will read that file's values through out all classes in the app until it is restarted where it will go back to the default file:

public class Main extends Game {
public SpriteBatch batch;
public ShapeRenderer renderer;
private Assets assets;

//Local Preferences
public Preferences preferences;

public Main(utilsInterface utils){
    this.utils = utils;
}
@Override
public void create () {
    batch = new SpriteBatch();
    renderer = new ShapeRenderer();
    assets = new Assets();
    preferences = Gdx.app.getPreferences("prefs_1");

    setScreen(new SplashScreen(this));
}
@Override
public void render () {
    super.render();

}
@Override
public void resize(int width, int height) {
    super.resize(width, height);
}

@Override
public void dispose() {
    super.dispose();
    assets.dispose();
    batch.dispose();
    renderer.dispose();
}
@Override
public void pause() {
    // TODO Auto-generated method stub
    super.pause();
    // Logs 'app deactivate' App Event.
    // AppEventsLogger.deactivateApp(this);
}
@Override
public void resume() {
    // TODO Auto-generated method stub
    super.resume();
    //Assets.manager.finishLoading();
    // Logs 'install' and 'app activate' App Events.
}

}

NOTE* I use the same instance of Preferences from the main class throughout the whole app.


Solution

  • Yes, this will work.

    If you use a different settings file, it will use the settings of that file. Just make sure to have default values for all settings so that if a new file is created (when you open a file that does not exist, write to it and flush it) you can still use it without it having all settings written to it.