Keeping active state in Android?

Hi guys I have one ColorPicker

in my application. When I set the color selected ColorPicker

to the background Activity

it works. But when I restart the app the color will change to default! How to save the state Activity

? Is it possible? Thanks in advance.

+3


source to share


2 answers


So, for example, you can keep a color like this (I just put a hex reference for the color, but you can change it to whatever you want):

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));
    }
}

      

+3


source


Andy The answer is correct. However, I thought I would be responsible for saving and loading preferences. These are generic Save / Load methods for strings. This is what I use in all my actions. This could save you a lot of headaches down the road!



 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;
    }

      

+2


source







All Articles