boolean in sharedPreferences not always save correcly - android

I have a strange issue. In One activity I have list with checkbox fields, the state of check box depends of shared prefrence, but it's work sometimes and sometimes not(It means sometimes when I checked the checkbox then back to the previous activity, and return into my checkBox activity the sharedPrefrences value is not changed). I thought it's happend because I'm change the activity too quick so i put saving logic in thread but got the same problem.
Here is some code that I've tried:
public final static String PREFERENCES_NAME = "USER_PREFERENCES";
public final static String PLAY_REQUIRED = "PLAY_REQUIRED";
sharedPreferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
recordCheckBox=(CheckBox)findViewById(R.id.recordRequiredCheckBox);
recordCheckBox.setChecked(sharedPreferences.getBoolean(PLAY_REQUIRED,true));
findViewById(R.id.playRequiredItem).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor preferencesEditor = sharedPreferences.edit();
if(recordCheckBox.isChecked()) {
recordCheckBox.setChecked(false);
preferencesEditor.putBoolean(PLAY_REQUIRED, false).apply();
preferencesEditor.commit();
Log.i("kamil","AfterSetFalseCheckBox :: "+ sharedPreferences.getBoolean(PLAY_REQUIRED,true));
}
else {
recordCheckBox.setChecked(true);
preferencesEditor.putBoolean(PLAY_REQUIRED, true).apply();
preferencesEditor.commit();
Log.i("kamil","AfterSetTrueCheckBox :: "+ sharedPreferences.getBoolean(PLAY_REQUIRED,true));
}
}
});

I think this is happened because whenever you put the value in sharedpreference than value inserted in one sharedprefrences, and when you get the value from sharedpreference is getting from another sharedpreference. So, I suggest you create proper helper class for sharedpreference and use it whenever you want.
Here is the example of that:
public class PreferenceHelper {
public static SharedPreferences AppPreference;
// Preference name for app.
public static final String APP_PREFERENCE_NAME = "app_preference_name";
/**
* Set boolean value to shared-preference.
*
* #param key Key for store boolean value to shared-preference.
* #param value Boolean value to be stored in shared-preference for given key.
*/
public static void putBoolean(Context context,String key, boolean value) {
AppPreference = context
.getSharedPreferences(APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
Editor editor = AppPreference.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**
* Get boolean value from shared-preference.
*
* #param key Key for getting boolean value from shared-preference.
* #param defaultValue Default boolean value that is returned if given key is not found in
* preference.
* #return string Boolean value from shared-preference for given key.
*/
public static boolean getBoolean(Context context,String key, boolean defaultValue) {
AppPreference = context
.getSharedPreferences(APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
boolean string = AppPreference.getBoolean(key, defaultValue);
return string;
}
}
and use it like:
To set value:
PreferenceHelper.putBoolean(getApplicationContext(),"key",value);
To get value:
Boolean boolean = PreferenceHelper.getBoolean(getApplicationContext(),"key",defalut-value);

You can used below method for set and get boolean value.
/For Set Boolean Value in Preference/
public void setBooleanValue(String key, boolean value, Context context) {
SharedPreferences preferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/For Get Boolean Value in Preference/
public boolean getBooleanValue(String key, Context context) {
SharedPreferences preferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
boolean value = preferences.getBoolean(key, false);
return value;
}

Related

SharedPreferencies have different values for the same key

I am having troubles using SharedPreferences in an Android app, and I need to get clear on it.
To avoid issues I have created a separated class for all maters regarding SharedPreferences to be used in the app.
This is the class:
public class SharedPreferencesClasMiPaciente {
SharedPreferences prefs;
Context context;
private static String PREFS = "MiPaciente";
public static SharedPreferences getPrefs(Context context){
return context.getSharedPreferences(PREFS,Context.MODE_PRIVATE);
}
public static void insertData(Context context,String key,String value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putString(key,value);
editor.commit();
}
public static void insertDataInt(Context context,String key,Integer value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putInt(key,value);
editor.commit();
}
public static void insertDataLong(Context context,String key,Long value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putLong(key,value);
editor.commit();
}
public static void insertStringSet(Context context,String key,Set<String> value){
getPrefs(context).edit().putStringSet(key,value).commit();
}
public static String retriveData(Context context,String key){
return getPrefs(context).getString(key,"no hay datos");
}
public static int retriveDataInt(Context context,String key){
return getPrefs(context).getInt(key,0);
}
public static long retriveDataLong(Context context,String key){
return getPrefs(context).getLong(key,0);
}
public static Set<String> getStringSet(Context context, String key){
return getPrefs(context).getStringSet(key,null);
}
public static void deleteData(Context context,String key){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.remove(key);
editor.commit();
}
}
I try to call this class every time I need to get or insert new SharedPreferences Data.
For now, to retrieve data inside a Fragment, I am using this code:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(getContext(),"hayFotos");
To insert data inside a Fragment, I am using this code:
SharedPreferencesClasMiPaciente.insertData(getContext(),"codigo_exploracion_actual",cod_exploracion);
To retrieve data in an Activity, I am using this code:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(this,"hayFotos");
To insert data in an Activity, I am using this code:
SharedPreferencesClasMiPaciente.insertDataInt(getApplicationContext(),"hayFotos",1);
This way is working but not always, there is another fragment where using the same methods, it is getting a different value for the same key:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(getContext(),"hayFotos");
Log.d("test shared","test shared hay fotos "+hayFotos);
At this case I am always getting the value 0 for key "hayFotos".
Is there a way to get SharedPreferences data on all fragments and activities inside an app?

Why Static Shared Preferences are not saved?

I want to access Shared preferences static way to avoid using excessive code, but when I read shared preference, looks like was not saved whith the static method "setSyncDBIsNeeded()", what I'm doing wrong?
MyApplication code:
public class MyApplication extends Application {
private static MyApplication instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(Realm.DEFAULT_REALM_NAME)
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
public static Context getContext() {
return instance.getApplicationContext();
}
}
My preferences activity:
public class PreferenceController {
SharedPreferences sharedPreferences;
private static String project = "com.example.myproject";
public PreferenceController() {
sharedPreferences = MyApplication.getContext().getSharedPreferences(project, Context.MODE_PRIVATE);
}
public PreferenceController(Context context) {
sharedPreferences = context.getSharedPreferences(project, Context.MODE_PRIVATE);
}
/* getters and setters */
// Static methods
public static void setSyncDBIsNeeded(boolean value) {
Log.d("PREFCON","Setted DBSyncNeeded : "+value);
getSharedPrefferences().edit().putBoolean("DBSyncNeeded", value);
}
public static boolean getSyncDBIsNeeded() {
Log.d("PREFCON","DBSyncNeeded: "+getSharedPrefferences().getBoolean("DBSyncNeeded", false));
return getSharedPrefferences().getBoolean("DBSyncNeeded", false);
}
private static SharedPreferences getSharedPrefferences() {
return MyApplication.getContext().getSharedPreferences(project, Context.MODE_PRIVATE);
}
}
Then in another class I do:
PreferenceController.setSyncDBIsNeeded(true);
PreferenceController.getSyncDBIsNeeded();
and its printed in Log:
07-14 14:24:04.665 27658-27658/com.example.myproject D/PREFCON: Setted DBSyncNeeded : true
07-14 14:24:04.665 27658-27658/com.example.myproject D/PREFCON: DBSyncNeeded: false
Try this:
SharedPreferences.Editor editor = getSharedPrefferences().edit();
editor.putBoolean("DBSyncNeeded", value);
editor.commit();
You have to remember to update the changes made to the SharedPreferences, so SharedPreferences actually save it.
Inserted into your code:
public static void setSyncDBIsNeeded(boolean value) {
Log.d("PREFCON","Setted DBSyncNeeded : "+value);
SharedPreferences.Editor editor = getSharedPrefferences().edit();
editor.putBoolean("DBSyncNeeded", value);
boolean completed = editor.commit();
Log.e("PREFCON", "Updating SharedPreferences was " + completed + "!";
}
By adding a boolean value to be set to editor.commit you can easily know if it was a success or not. According to the documentation the commit() method returns a boolean value based on if it completed or not. True means the editing was successfull, while false means something went wrong.
You need to use commit or apply to actually perform the request.
Commit your preferences changes back from this Editor to the
SharedPreferences object it is editing. This atomically performs the
requested modifications, replacing whatever is currently in the
SharedPreferences.
public static void setSyncDBIsNeeded(boolean value) {
Log.d("PREFCON","Setted DBSyncNeeded : "+value);
getSharedPrefferences().edit().putBoolean("DBSyncNeeded", value).apply();
}

How to retrive SharedPreferences, which where saved from another activity in Android?

I have situation in my app. Let's take two activities A & B . A is the main activity(which gets started when app is opened). B is started from A. I have a check box in B, who's boolean value using isChecked() method is assigned to a boolean called value & is saved to SharedPreferences. The code for saving to SharedPreferences is
SharedPreferences sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("value", value);
editor.commit();
Now I want to read this value from activity A(i.e the Main activity), during opening the app and depending on this value I need to perform additional operations.
The code I use to retrieve the value is
SharedPreferences sharedPreference=PreferenceManager.getDefaultSharedPreferences(this);
boolean value=sharedPreferences.getBoolean("value", false);
The problem is that I am not able to retrive this values in activity A.Since the value is not retrieved the operations depending on value are not carried out.Also no matter how many times I check the checkBox upon restarting the application CheckBox remain unchecked in activity B. What is the problem?
You can create singleton class that manage app's preferences (do not forget make your own YourAppSingleton class):
public final class PreferencesUtil {
private PreferencesUtil() {}
public static float getFloatValue(String key, float defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getFloat(key, defaultValue);
}
public static void setFloatValue(String key, float value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putFloat(key, value);
editor.commit();
}
public static long getLongValue(String key, long defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getLong(key, defaultValue);
}
public static void setLongValue(String key, long value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void setIntValue(String key, int value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static int getIntValue(String key, int defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getInt(key, defaultValue);
}
public static void setStringValue(String key, String value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringValue(String key) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, null);
}
public static String getStringValue(String key, String defValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, defValue);
}
public static boolean getBooleanValue(String key, boolean defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getBoolean(key, defaultValue);
}
public static void setBooleanValue(String key, boolean value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void clearValue(String key) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.remove(key);
editor.commit();
}
private static SharedPreferences getSharedPreferences() {
return YourAppSingleton.getInstance().getSharedPreferences(YourAppSingleton.getInstance().getString(R.string.app_name), Context.MODE_PRIVATE);
}
}
Application class:
public class YourAppSingleton extends Application {
private static YourAppSingleton instance = null;
public void onCreate() {
super.onCreate();
instance = this;
}
public static YourAppSingleton getInstance() {
return instance;
}
}

SharedPreferences cleared if remove the app from recent activity android

I'm using SharedPreferences in my project with MODE_PRIVATE, when i cleared the app from recent activity list, and opens the app again, all my preference data is cleared.
I'm using this class fro setting and getting preference.
public class Preferences {
private Context _context;
private SharedPreferences _preferences;
private Editor _editor;
private String prefName = "pref";
//=====
public Preferences(Context context){
_context = context;
_preferences = this._context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
_editor = this._preferences.edit();
}
//=====
public Preferences commit(){
_editor.commit();
return this;
}
//=====
public Preferences set(String key, String value){
_editor.putString(key, value);
return this;
}
//=====
public String get(String key){
return _preferences.getString(key, "");
}
//=====
public Preferences set(String key, int value){
_editor.putInt(key, value);
return this;
}
//=====
public int getInt(String key){
return _preferences.getInt(key, 0);
}
//=====
public Preferences setBoolean(String key, boolean value){
_editor.putBoolean(key, value);
return this;
}
//=====
public void removeKey(String key){
_editor.remove(key);
}
//=====
public boolean getBoolean(String key){
return _preferences.getBoolean(key, false);
}
}
can any one help me ...??
change your set method like this
public Preferences set(String key, int value){
_editor.putInt(key, value);
_editor.commit();
return this;
}
you don't need separate commit() into independent method.
good luck
this is another example, in this example i create a value that save my city name and when my app lunched i check for existing , if exist the value of that key returned to me.
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// define sp
sp=getSharedPreferences("test", Context.MODE_PRIVATE);
// get sp value if exist
if(sp.contains("EkbatanApp")){
String spResult=sp.getString("EkbatanApp", "");
}
}
//save key
public void SaveSettingOnClick(View v){
Editor editor=sp.edit();
editor.putString("EkbatanApp", "Borujerd");
editor.commit();
}

Access another classes's SharedPreferences from BroadcastReceiver

I have a savePreferences and loadPreferences method written as follows in MyClass (which is an Activity):
private void savePreference(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean toggleValue = sharedPreferences.getBoolean("ToggleValue", true);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public void loadPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean toggleValue = sharedPreferences.getBoolean("ToggleValue", true);
if (toggleValue) {
toggle.setChecked(true);
alertStatus=true;
} else {
toggle.setChecked(false);
alertStatus=false;
}
myHold.setStatus(alertStatus);
}
I also have a BroadCastReceiver class named MyBroadCast
In the onReceive() method of the BroadCastReceiver, I want to call loadPreferences() to load the preferences. How can I do so? I tried making an object of MyClass and calling .loadPreferences() but it would give me a null pointer exception in this line of the loadPreferences class:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
You can add a static method inside your Activity to encapsulate the read calls to SharedPreferences:
public static boolean loadTogglePreferences(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getBoolean("ToggleValue", true);
}
To reduce code redundancy you might want to use this methods in you existing code:
public void loadPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean toggleValue = loadTogglePreferences(this);
toggle.setChecked(toggleValue);
alertStatus = toggleValue;
myHold.setStatus(alertStatus);
}
If you are reading more than a few itms from SharedPreferences, you should definitely reuse the SharedPreferences object instead of creating a new one for every item.
Or, you could just reference "ToggleValue" as a public static final String and read the default SharedPreferences in the receiver yourself:
public static final String PREFS_TOGGLE = "ToggleValue";

Categories

Resources