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";
Related
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();
}
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;
}
}
I want to get a string from my shared preference file and use for more classes, but I don't know why not work.
My reader class is:
import android.app.Activity;
import android.content.SharedPreferences;
public class A {
public static String url2;
public void execute() {
String URLPref = "URL";
SharedPreferences prefs = getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
url2 = prefs.getString(URLPref , "");
}
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
return null;
}
}
And the second class that uses the string
public class SearchHome extends Activity {
static String url2;
A cls2= new A();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
cls2.execute();
url2 = A.url2;
Toast.makeText(getApplicationContext(),"URL:" + url2 ,
Toast.LENGTH_LONG).show();
...
Sorry for my bad english, I never learned.But I'm trying!
You need to pass the Context to your class A, because you can get the SharedPreferences from a Context object. NOTE, an Activity is a Context to some extend
public class A {
public static String url2;
/** #param context used to get the SharedPreferences */
public void execute(Context context) {
String URLPref = "URL";
SharedPreferences prefs = context.getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
url2 = prefs.getString(URLPref , "");
}
}
And then pass the Context to your execute method
public class SearchHome extends Activity {
static String url2;
A cls2= new A();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
// pass context 'this' to the execute function
// This works, because SearchHome extends Activity
cls2.execute(this);
url2 = A.url2;
...
if your data is not confidential it would be a lot easier if you can make a class specially for shared preference and have other activities access it. you will save a lot of time and code will be a lot simpler to follow up
public class HelperShared {
public static final String score = "Score";
public static final String tag_User_Machine = "tag_User_Machine",
tag_Machine_Machine = "tag_Machine_Machine",
tag_Draw_Machine = "tag_Draw_Machine",
tag_Total_Machine = "tag_Total_Machine";
public static SharedPreferences preferences;
public static Editor editor;
public HelperShared(Context context) {
this.preferences = context.getSharedPreferences(score,
Activity.MODE_PRIVATE);
this.editor = preferences.edit();
}
/*
* Getter and Setter methods for Machine
*/
public void setUserMachine(int UserMachine) {
editor.putInt(tag_User_Machine, UserMachine);
editor.commit();
}
public void setMachineMachine(int MachineMachine) {
editor.putInt(tag_Machine_Machine, MachineMachine);
editor.commit();
}
public void setDrawMachine(int DrawMachine) {
editor.putInt(tag_Draw_Machine, DrawMachine);
editor.commit();
}
public void setTotalMachine(int TotalMachine) {
editor.putInt(tag_Total_Machine, TotalMachine);
editor.commit();
}
public int getUserMachine() {
return preferences.getInt(tag_User_Machine, 0);
}
public int getMachineMachine() {
return preferences.getInt(tag_Machine_Machine, 0);
}
public int getDrawMachine() {
return preferences.getInt(tag_Draw_Machine, 0);
}
public int getTotalMachine() {
return preferences.getInt(tag_Total_Machine, 0);
}
}
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
return null;
}
problem is here.
return null;
you have to return valid SharedPreferences object. otherwise you will always get NullPointerException.
Call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
Call this when you want to get a pref:
getPref("myKey", getApplicationContext());
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
Different Modes:
1 MODE_APPEND
This will append the new preferences with the already exisiting preferences
2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded
4 MODE_PRIVATE
By setting this mode , the file can only be accessed using calling application
5 MODE_WORLD_READABLE
This mode allow other application to read the preferences
6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Read More
You just need to make shared prefrences object in class where you want to have data
SharedPreferences prefrences = getSharedPreferences("my prefs",MODE_PRIVATE)
Editor editor = prefrences.edit();
String s = edit.getString("your key",value);
hope it helps !
Do I need to call edit SharedPreferences everytime before I change the preferences and commit or can I do that just once in the costructor?
Is this correct ?
public class MyPreferencesClass {
private Context ctx;
private static SharedPreferences settings;
private static SharedPreferences.Editor editor;
// Constructor Class //
public MyPreferencesClass(Context context) {
this.ctx = context;
settings = ctx.getSharedPreferences(CUSTOM_PREFS_NAME, 0);
editor = settings.edit(); // Called Only once in constructor not not everytime in edit methods
}
public static void setSomePref1(Boolean boolValue) {
// editor = settings.edit(); Not required everytime
editor.putBoolean(PREFS_1, boolValue);
editor.commit();
}
public static void setSomePref2(Boolean boolValue) {
editor.putBoolean(PREFS_2, boolValue);
editor.commit();
}
...
}
you should be able to use SharedPreferences.Editor instance as long as it's valid so no need to call SharedPreferences#edit() every time.
Whenever I try to add this line it crashes my app. Am I not putting it in the right spot?
preferences.registerOnSharedPreferenceChangeListener(myActivity.this);
Here is my class
class Simulation extends View {
// I declare my program variables here
public Simulation(Context context) {
super(context);
// get the preferences
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
preferences
.registerOnSharedPreferenceChangeListener(myActivity.this);
String storedPreference = preferences.getString("nPref", "0");
}
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
Log.i(TAG, "preferences changed!");
}
}
Thanks!
Do like this
SharedPreferences.OnSharedPreferenceChangeListener prefListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if (key.equals("date")) {
}
}
};
and
preferences.registerOnSharedPreferenceChangeListener(prefListener);
One note about the Answer, the prefListener needs to be a class field, not a local variable or it may get garbage collected.
SharedPreferences.onSharedPreferenceChangeListener not being called consistently