Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the Activity state in android?

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!!!

like image 584
Ajinkya More Avatar asked Sep 03 '25 05:09

Ajinkya More


2 Answers

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));
    }
}
like image 50
Andy Joyce Avatar answered Sep 04 '25 18:09

Andy Joyce


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;
    }
like image 20
Petro Avatar answered Sep 04 '25 18:09

Petro