I cannot get Mono for Android activity preference to work - android

In my mono for android app I want to save a user setting for an activity into the activities preference. I do this whenever the user changes this value:
ISharedPreferences prefs = GetPreferences(FileCreationMode.Append);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutInt(NO_PIXELS_PER_HOUR_KEY, m_noPixelsPerHour);
editor.Commit();
where NO_PIXELS_PER_HOUR_KEY is:
private const string NO_PIXELS_PER_HOUR_KEY = "PIXELS_PER_HOUR";
This value should then be loaded again in the actvity's OnCreate method:
ISharedPreferences preferences = GetPreferences(FileCreationMode.Append);
int tempNoPixelsPerHour = preferences.GetInt(NO_PIXELS_PER_HOUR_KEY, -1);
if (tempNoPixelsPerHour == -1)
m_noPixelsPerHour = (int)(m_deviceHeight * 0.25);
else
m_noPixelsPerHour = tempNoPixelsPerHour;
The problem is that the value does not seem to be persisting! Whenever I go out of the activity and back into it the default value of -1 is returned. I don't know whether it is not saving properly or not loading properly. Any help would be appreciated!
Thanks,
Dave

I dont know about mono for android but in android we call getsharedpreferences() in java. Here you're calling only the preferences which can be any preference but the settings preference. You can try something like getdefaultsharedpreference or something like that.
EDIT : I'm not sure but you can try this..
ISharedPreferences _preferences = PreferenceManager.GetDefaultSharedPreferences(your_context)

Related

How to save value of a string even after the activity/app is destroyed?

I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);

Android - Saving in Shared preferences stopped working

In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?

How to keep information about an app in Android?

I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.

Shared Preferences issue, not freeing the value after calling clear

In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it:
SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit();
Notificationeditor.putString("notificationCount", notificationCountValue);
Notificationeditor.commit();
And the following code on onClick():
SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();
System.out.println("Saved in SP clearedNotification: "+ clearNotification);
I was printing the value after clearing it but still I was getting the same value.
What am I missing?
Any kind of help will be appreciated.
getDefaultSharedPreferences and getSharedPreferences("notification_prefs", );
returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", );
getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter

Create method that returns value gotten at applucation start

I'm developing an application where I want to find out what volume the user had when he started my app from a method thats not onCreate(). I have created an int based on the current volume inside my onCreate but since it can't return anything I don't know how to get my int from there. It's very important that I use the int I generated at in onCreate().
How can this be done?
#pawegio right, if you want to use same vol level what user set up, use preferences.
This is how to:
WRITE into preferences
SharedPreferences pref =
context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
/*
* Get the editor for this object. The editor interface abstracts the implementation of
* updating the SharedPreferences object.
*/
SharedPreferences.Editor editor = pref.edit();
/*
* Write the keys and values to the Editor
*/
editor.putInt("VolumLevel", 60);
/*
* Commit the changes. Return the result of the commit.
*/
e.commit();
READ from preferences
SharedPreferences pref = context.getSharedPreferences("MyAppPreferences", MODE_PRIVATE);
int volLevel = pref.getInt("VolumLevel", 50 /*Default if value wasn't setup yet*/);
return volLevel;
If I well understood you, you should use: SharedPreferences to save that value.

Categories

Resources