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!!!
Asked
Active
Viewed 142 times
4

Ajinkya More
- 425
- 1
- 3
- 15
-
3considering you're quitting the application and opening it, you're supposed to store the data in `SharedPreferences`. – EpicPandaForce May 16 '15 at 14:50
-
Can you show me an example? – Ajinkya More May 16 '15 at 14:51
-
1http://developer.android.com/guide/topics/data/data-storage.html#pref – antonio May 16 '15 at 14:54
-
[example question from stackowerflow](http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) – Kasun Dissanayake May 16 '15 at 14:56
-
Please guys can you show me an example? I'm unable to study this code and know how to use it! – Ajinkya More May 16 '15 at 14:56
-
But how to make the color save? Should I post my code? – Ajinkya More May 16 '15 at 15:00
2 Answers
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