Shared Preferences is not working, android? - android

The following method was working, but now it is not writing my integer into file.
public void writeChpNum(int num) {
SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).apply();
}
and this is how I get from Main class:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
chapterNum = prefs.getInt("chapter", 1);
Method did not work in this situation:
writeChpNum(1);
writeLastLine("0");
boolean deleted = file.delete();
boolean deleted2 = file2.delete();
boolean deleted3 = file3.delete();
boolean deleted4 = last.delete();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Here, I want to restart everything and exit, so I am removing files, but for chapters I just have to write "1"-chapter. However, it did not write.
Is this because I am exiting the app?

Context object will not be available in other Activities when you access it like that. Try passing it context in method as well if you want to write this method to only one class. make method static so you don't need to create activity object.
Edit
Based on your new code for exiting app you need commit() instead of apply()
Ref: https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
public static void writeChpNum(Context c, int num) {
SharedPreferences prefs = c.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).commit() ;
}

Related

SharedPreferences does not store value

I am currently working with SharedPreferences in Android, and I encountered a weird behavior I cannot explain. This is my code:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
appPreferences.edit().putBoolean("launched_before", true);
appPreferences.edit().apply();
appPreferences = null;
appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false); //this is false
The value that I write to my SharedPreferences is not being saved. I know I could use getDefaultSharedPreferences(), but I do not want to do this here, as the default file stores other values.
When I use commit() instead of apply(), the return value of commit() is true, but I still cannot load the file correctly.
This happens because your code doesn't do what you think. When you call edit(), it does not start an "edit transaction". Instead it returns a new instance of Editor object each time you call it. So let's look at this code:
SharedPreferences appPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);
// Here you create a FIRST Editor object, which stores the modification
// You never call apply() on this object, and thus your changes are dropped.
appPreferences.edit().putBoolean("launched_before", true);
// Here you create a SECOND Editor object (which has no modifications)
// and you call apply() on it, thus changing nothing.
appPreferences.edit().apply();
You created the first editor object which you put settings in, but you called apply on the second editor object which had no changes. Since you never called apply() on the editor object which had modification, your change was never saved.
The fix is obvious - use a single instance of Editor for your modification, and call apply/commit on this instance:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = appPreferences.edit();
ed.putBoolean("launched_before", true);
ed.apply();
Here you can use as key "com.yourdomain.yourapp.your_key_name" and for each value use another key...try this
private SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
public void putBoolean(String key, boolean value) {
checkForNullKey(key);
preferences.edit().putBoolean(key, value).apply();
}
public boolean getBoolean(String key) {
return preferences.getBoolean(key, false);
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}

Save/Load problems with SharedPreferences in Android

and sorry if this is a stupid question. I'm learning to use SharedPreferences and I have a bit of a problem:
I'm using this code to save to SharedPreferences:
public void saveInMemory(String[] saveThis){
StringBuilder sb = new StringBuilder();
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
editor = prefs.edit();
for (int i = 0; i < saveThis.length; i++) {
sb.append(saveThis[i]);
sb.append(";");
}
editor.putString("listaOIB", sb.toString());
editor.commit();
}
And this code to load saved values:
public String loadFromMemory(String id){
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
return prefs.getString(id, "NOPREFSAVED");
}
I've also already declared prefs and editor outside, so that shouldnt be a problem:
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
Now, my problem is that when I enter this activity and save files that i received from other activity(via putExtra, if that helps), then proceed to load it everything works fine.
Then I reenter my activity without sending any files to it (from other activity) and try to use loadFromMemory() and it doesnt work. My understanding is that it should have saved files when I entered Activity for the first time, and then load it whenever I want.
Any help?
add the method and call when you add and other is call when you get
//this method is call when you add the data
public static void setAlarmHourTime(String value, Activity activity) {
SharedPreferences.Editor pref = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE).edit();
pref.putString("alarmhourtime", value);
pref.commit();
}
//this method is call when you retrive the data
public static String getAlarmHourTime(Activity activity) {
SharedPreferences prefs = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE);
return prefs.getString("alarmhourtime","7");
}
if you want to retrieve content saved in editor.putString("listaOIB", sb.toString());, then the id you pass in loadFromMemory should be "listaOIB".
Is it the case?

Retrieving SharedPreferences Data Failure

I am trying to use SharedPreferences, but I keep encountering the following problem.
In the class where I create the file & add information to it I do the following:
private SharedPreferences prefs = null;
private SharedPreferences.Editor editor = null;
public void setStuff (String info, boolean save, Context appCT) {
if (prefs == null && editor == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
editor = prefs.edit();
}
editor.putString("Custom", info);
editor.commit();
}
Which, to my knowledge, runs perfectly. However, when I attempt to access that information I stored in 'preferences' from another other class:
private static SharedPreferences prefs = null;
private static String custom = null;
public static void getStuff(Context appCT) {
if (prefs == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
custom = prefs.getString("Custom", null);
}
}
The value of custom is always null, as if I never stored the String. Can anyone tell me why this is?
I have searched for an answer; I am using a context for getSharedPreferences, I have following all of the instructions & tutorials I have found with no varying results.
NOTE: The classes are not in the same application. Is this a problem? Can I not access the preferences of another application?
Thank you.
getStuff() only sets custom if prefs is null. So, the method will do nothing after the first time it is called. Or, if prefs is set before this method is ever called, then the method will never do anything.
The method should look like this, instead:
public static void getStuff(Context appCT) {
if (prefs == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
}
custom = prefs.getString("Custom", null);
}
Also, if the 2 classes are in different applications, Context.MODE_PRIVATE will prevent them from sharing the SharedPreferences. You can use Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE instead, but that is very unsafe and deprecated in API level 17. See the information at the above links to see what is recommended instead.
I think you need do to a prefs = PreferenceManager.getDefaultSharedPreferences(yourcontext); first.

Android initialization with SharedPreferences

I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
Try something like this.... adding methods for each variable you want to save.
public class PreferenceManager {
private static PreferenceManager self;
private SharedPreferences preferences = null;
private SharedPreferences.Editor editor = null;
private boolean isInitialised = false;
private static final String MY_PREFERENCE = "mypreferencekey";
private String myPreference = null;
public void initialise(Context context) {
if (!isInitialised) {
preferences = context.getSharedPreferences("MyPreferencePlace", Context.MODE_PRIVATE);
editor = preferences.edit();
loadPreferences();
isInitialised = true;
}
}
public static PreferenceManager getInstance() {
if (self == null) {
self = new PreferenceManager();
}
return self;
}
private PreferenceManager() {
}
public void setPreference(String newPreferenceValue) {
this.myPreference = newPreferenceValue;
savePreferences();
}
public String getPreference(){
return myPreference;
}
private void savePreferences() {
editor.putString(MY_PREFERENCE, myPreference);
editor.commit();
}
private void loadPreferences() {
myPreference = preferences.getString(MY_PREFERENCE, null);
}
}
All the SharedPreferences need is a context and it can be initialized. As your application always opens an Activity to start with, you always have a context to work with.
I would advise you to wrap the SharedPreferences in a Singleton class and just pass a context as parameter at the getInstance method. You should be able to access your shared preferences at all Activities this way.
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon

Sharedpreferences - crashes on startup

I'm trying to write an activity that would be able to both write and read sharedpreferences data.
I initiate SharedPreferences at the beginning
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Then this function writes an int to SP and call another function.
public void SetHue(int i)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", i); // value to store
editor.commit();
ApplyHue();
}
this other function should read that int from SP...
public void ApplyHue()
{
int hueInt = preferences.getInt("storedInt", 0);
/// adjust background image hue according to hueInt.
}
I can't simply pass this int from one function to another, because I need other activities to be able to run ApplyHue() function, which should use hueInt from memory.
What do you think might be causing it to crash?
Thanks!
I think you wrote this line in the class before your onCreate method.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Decalare SharedPreferences preferences; in the class and then in onCreate
preferences = PreferenceManager.getDefaultSharedPreferences(this);
Hopefully your problem will be solved

Categories

Resources