4

Hello guys I've ColorPicker in my app. When I set the color selected by ColorPicker to the Activity background, it works. But when I restart the app, the color changes to default! How to save the state of Activity? Is it possible? Thanks in advance!!!

Ajinkya More
  • 425
  • 1
  • 3
  • 15

2 Answers2

3

So for example you can save the color like this (I've just put a hex color reference but you can change it to whatever you wish):

public void setBackgroundColor() {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("color", "#FFFFFF");
    editor.commit();
}

Then just make sure you call this method every time it loads / reloads:

public void getBackgroundColor() {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    if (sharedPreferences.contains("color")) {
        String myColor = sharedPreferences.getString("color", null);
        mybackground.setBackgroundColor(Color.parseColor(myColor));
    }
}
Bruno Parmentier
  • 1,219
  • 2
  • 14
  • 34
Andy Joyce
  • 2,802
  • 3
  • 15
  • 24
2

Andy's Answer is correct. However, I thought I would chime in on saving and loading preferences. These are universal Save/Load methods for Strings. It's what I use in all my activities. It can save you a lot of headaches in the future!

 public static String PREFS_NAME = "random_pref"; 

 static public boolean setPreference(Context c, String value, String key) {
        SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
        settings = c.getSharedPreferences(PREF_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    static public String getPreference(Context c, String key) {
        SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
        settings = c.getSharedPreferences(PREFS_NAME , 0);
        String value = settings.getString(key, "");
        return value;
    }
Petro
  • 3,484
  • 3
  • 32
  • 59