Android: Save and load settings

Its always good when an application remembers the last settings you've used. To add that functionality within your app, just add this class to your project.

/**
* This class is responsible for storing and loading the last used settings for the application.
*
* @author twig
*/
public class Settings {
public boolean music = true;
public boolean sfx = true;
public int games_played = 0;
public int high_score = 0;

public Settings() {
this.loadSettings();
}

public void loadSettings() {
SharedPreferences settings = G.activity.getPreferences(Activity.MODE_PRIVATE);

this.music = settings.getBoolean("music", this.music);
this.sfx = settings.getBoolean("sfx", this.sfx);
this.games_played = settings.getInt("games_played", this.games_played);
this.high_score = settings.getInt("high_score", this.high_score);
}

public void saveSettings() {
SharedPreferences settings = G.activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("music", this.music);
editor.putBoolean("sfx", this.sfx);
editor.putInt("games_played", this.games_played);
editor.putInt("high_score", this.high_score);

editor.commit();
}
}

When you create an instance of it, it'll automatically load up the old settings and the set defaults if it can't find it.

Remember, you'll still have to save when the application exits!

/**
* Activity is stopped by Android OS.
*/
@Override
protected void onStop(){
super.onStop();

G.savePreferences();
}
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog