Saving the Activity state in android? - 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!!!

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

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

Related

unable to clear my sharedPreferences using editor.clear().commit();

I am working on an android project where I have a scenario such as :
I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.
but the problem is when I closed activity and again open that activity; my data still visible in TextView.
even when I cleared it in onDestroy().
here is my code for send data :
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("address", (String) Address);
editor.commit();
finish();
here is my code to set and clear data:
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
String n = settings.getString("name", "");
String a = settings.getString("address", "");
name.setText(n);
location.setText(a);
}
#Override
protected void onDestroy() {
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
here is my preference manager class :
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "sara";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.clear().commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.
I'm not sure where you are using SharedPreference object to set data in it. But I guess this is the problem:
In this activity, you are clearing SharedPreferenece correctly.
You go back to previous Activity. And the previous activity, sets data to shared preference, again. So SharedPreference is not empty anymore.
You go to second activity (which you remove shared preference data in onDestroy()). As shared preference is not empty, you are seeing data again.
So check the code again and feel free to ask any questions.
Try check the logs to make sure you are really going 'onDestory' well.
#Override
protected void onDestroy() {
Log.d("address", "onDestory");
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
There is no problem with the code for creating and removing SharedPreferences.

Android SharedPref not saving on restart

In my Android app I can display a popup when the app is updated (Based on versionCode). In the popup I have put a checkbox saying "dont show me again". When I click on that, it will save in the sharedpref the versionCode and wont display the popup anymore.
I have run against something odd behaviours where when I have saving the new Set<String>, it did indeed was saving it but when my app restarts the settings is lost.
Set<String> readAnnouncement = getReadAnnouncement(this);
readAnnouncement.add(String.valueOf(versionCode));
PreferenceManager.getDefaultSharedPreferences(this).edit().putStringSet(KEY_READ_ANN, readAnnouncement).apply();
If I break point on readAnnouncement.add, I can set for example the list having 2 items. When I execute the PreferenceManager.getDefaultSharedPrefer... and then execute getReadAnnouncement(this); the value is there, all good.
If I restart the app and check again getReadAnnouncement(this); the new value is gone.
By clearing the cache the problem disappeared... Why was is not saving? Is it possible the SharedPreference were full?
Try like this.
import android.content.Context;
import android.content.SharedPreferences;
/**
* #author VIVEK
* This class deals in with setting Cache value for complete app.
*/
public class SharedPrefUtil{
/*Set Boolean value in shared preferences */
public static void setSharedPref(Context context, String key, boolean value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/*get Boolean value in shared preferences */
public static boolean getSharedPref(Context context, String key, boolean defaultVal) {
boolean prefToken = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
prefToken = sharedPreferences.getBoolean(key, false);
return prefToken;
}
/*Set String value in shared preferences */
public static void setSharedPref(Context context, String key, String value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/*get String value in shared preferences */
public static String getSharedPref(Context context, String key, String defaultVal) {
String value = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
value = sharedPreferences.getString(key, defaultVal);
return value;
}
public static void cleanSharedPrefFile(Context context) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
} // End of main class over here ...
Now you want to set some value in Shared Pref then set like this
SharedPrefUtil.setSharedPref(MainActivity.this, "test", storeBuff);
Now when you need to get value from shared Pref then call like this
SharedPrefUtil.getSharedPref(MainActivity.this, "test", "default value");
In place of editor.commit() , use editor.apply()
BASICS:
getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.), which allow to have better access over your SharedPref file.

How to use SharedPreference to save score and name in a game?

I am creating my first android app and I don’t have enough knowledge in programming unlike other here. So please help me with this matter. I want to save player’s name and score. I’ve searched and read a lot about SharedPreference but was unable to understand it very well especially when I am already applying the codes on my activity. I have tried it twice and everytime I run it, it shows”Not Responding” message and closes. But when the codes for sharedpreference are not indicated there it works fine. So here’s how I want to do with these. On the first game, the very first score should be saved after the time is over (the user will be typing their name and click save). So when another user or player plays the game the Top Score should be indicated in the screen using a textview, below this Top Score textview is the Current Score textview. If the Current Score is greater than the Top Score then it should overwrite the score. If not then the Top Score should stay the same. How can I achieve this?
P.S. I have 3 different activities that needs this SharedPreferences but with the same functionalities. Thanks in advance. And please explain it more clearly (coz sometimes I can’t understand some words) thank you :)
This is the code i use, i put it in Oncreate
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name);
editor.putInt("score", score);
editor.commit();
I think following link will surely help you out SharedPreferences Explained in detail
.
Try this
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); //similar way you can push integer values
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.getString(key, null); //default value will be null in this case, if there is no such key
You can write a Utility class to reuse this methods wher you want. like below
public class PreferenceUtility {
public static void saveString(Activity activity, String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static String readString(Activity activity, String key, String defaultValue){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
return sp.getString(key, defaultValue);
}
}
static SharedPreferences sh_Pref;
public static String Preference_Name = "AppData";
public static String getPreference(String key, String Default,
Activity activity)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
return sh_Pref.getString(key, Default);
}
public static void setPreference(String key, String value, Activity activity)
{
if (value != null)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
Editor editor = sh_Pref.edit();
editor.putString(key, value);
editor.commit();
}
}
}
** Here a set and get value from SharedPreferences**

Loading up value from SharedPreferences

In my Application class, I have the following:
public void loadPrefs(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean soundValue = sharedPrefs.getBoolean("SOUND", false);
}
public void savePrefs(String key, boolean value){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sharedPrefs.edit();
edit.putBoolean(key, value);
edit.commit();
}
All OK there as far as I can tell.
Now in my main class which extends SurfaceView, I have the following:
myApp mySettings = (myApp)getContext().getApplicationContext();
Then I can save values like so: (Again from my surfaceView activity)
myPlanSettings.savePrefs("SOUND", false);}
However, what I just cannot work out is how to read the value back so I can set a local variable like so:
Boolean thisValue = (the value from the shared preferences).
Thanks for any help
Try this
public Object loadPrefs(String key,String defaul){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPrefs.get(key,default);
}
Cast it with the type while using getting the value
Basic usage:
boolean b=(Boolean)loadPrefs("value","default value")

error in saving the username at the launch of application in android

I am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();

Categories

Resources