Saving radio button value using sharedpreferences - android

First before i continue with this i want to know if i can use these sharedpreferences to do background calculations later on, or will i have to save them to a database to use to show them on other Activities/classes. If i do want to do calculations with numbers entered from this form will i have to change it from string to save to an int?
Thanks!

To save 1 or 2 values, Shared Preferences is better than SQLite.
SharedPreferences are singletons and cached process-wide. so you want to get it loaded as early as possible so you have it in memory before you need it.
Since in your case, it is 1 or 2 values, this should create minimal performance impact.

Related

Why does SharedPreferences need two keys?

I'm trying to build a single object that handles all my SharedPreferences, since they are mostly used in the whole app, and I don't quite Understand why it takes two keys to get a value.
The call looks like this:
context.getSharedPreferences(FirstKey, Context.MODE_PRIVATE).getString(SecondKey, default)
I get that its basically built up as a two dimensional array.
The FirstKey gives me a collection of key-value pairs I can use my SecondKey on to get my value. And I get that If I have dozens of SharedPreferences this might come in handy to manage them and prevent mixups/unwanted overwriting.
But is this necessary If I only have like 10 preferences I save anyway or is it reasonable to just use one FirstKey for all of my preferences?
But is this necessary If I only have like 10 preferences I save anyway
or is it reasonable to just use one FirstKey for all of my
preferences?
So for this case you can avoid the use of that FirstKey by using getDefaultSharedPreferences() like this:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("myKey", "myValue");
editor.apply();
or read already set preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String myPref = prefs.getString("myKey", "myDefaultValue");
I guess it is to encapsulate, organize and manage better groups (first key values) of data you want to store (second keys values). So in case you want for example to retrieve all settings preferences you can group them by a Settings file (first key). Or in case you would like to delete all stored values regarding a user preferences (preferred language, preferred currency.. ) then you can organize those data within a "UserPref" file (first key) and then you can iterate within it to either delete all of them when you logout or whatever pogic you see useful for your user experience.
First key
Retrieve and hold the contents of the preferences file
Second key
Retrieve and hold value in this file
You can use only your "FirstKey" for all your preferences and normally dev us it like this only. You can create multiple instances of shared preference by changing the "First key" at the time of getSharedPreference(). Suppose you want two different shared preference for two different modules in your project then change the "FirstKey" parameter, in this case, you have two be careful while storing and fetching data from preference as you have two different shared preference.
As you rightfully stated, the first key represents a group of key-value pairs (which is actually very similar to a single file) and the second key helps you fetch the values in that file/group.
I personally believe this design is great especially in cases where you may want to separate all your values into different categories. If your app is "small", you can save all your values in one single file/group. Otherwise, you can split all your values into separate files/groups.
I hope this helps.. Merry coding!

Best practice for saving 10 values : Shared Preferences with or without JSONObject?

I have 10 values (int and boolean) which I want to save, so I can load them whenever I need them (I need the different values at the same time which makes it easy). Is it overkill if I make one JSONString/(JSONObject) out of 10 values and save that string in SharedPreferences? Is it better practice to just store every single value like this:
editor.putInt("Volume", VolumeBar.getProgress());
editor.putInt("Difficulty", DifficultyBar.getProgress());
[...]
and to get it from SharedPreferences like this:
Volume = mPrefs.getInt("Volume", maxVolume);
Difficulty = mPrefs.getInt("Difficulty", 0);
I think it's better to create model with ten variables and convert it
to JsonString because you just put one strng value in SharedPref but it's issue that if you want to update one of it's values you have to retrieve the whole object and modify and set it back in sharedPref

Android save overall score

I've made a little android game and I have a problem saving the overall score which should be retrieved every time the app starts up again instead of just starting at the default 0 like it always does.
I looked at SharedPreferences but that seems to be more about saving high scores that won't change.
Is there a way for my save the a score which will be changed as more games are played?
I assume I'd need to do the following:
Retrieve the saved score
Put it into a variable
Change that variable
Save it again end of game or every-time it changes (depending on whether or not it affects performance)
Edit: Turns out SharedPreferences would work for this scenario. Now could someone please provide an answer of how to implement it?
I believe you can use Shared Preference for that purpose.
It can be used to save your score, overwrite the score and retrieve the score.
Shared preference uses the Key value pair.
I'm not sure why you'd come to the conclusion that SharedPreferences would be more suitable for non-changing values.
I think this is an excellent use case for it.
You could try other persistence options (such as integrating SQLite into your app) but this seems like the quickest option with the least amout of overhead.
Still, if you're interested in other options, I hope you've skimmed through the storage options in the Android documentation:
http://developer.android.com/guide/topics/data/data-storage.html
And, of course, using SharedPreferences will have to be done in conjunction with Application LifeCycle methods (such as onResume, onPause, etc):
http://developer.android.com/training/basics/activity-lifecycle/index.html
You can use a SQLite database to save the score value.
To retrieve you current score in the database use this query.
SELECT score from ScoreTable where id = userId;
Assign the retrieve value to a variable.
At the end of the game // Update the score value
int finalScore = initialscore + newScore
UPDATE ScoreTable SET score = finalScore WHERE id = userId

How to store values in preferences over one another

When i write anything into shared preferences it overwrites the previous value, how can i continuously inject values in preferences and fetch it out all at once like an array? I do not want to use database for this operation.
Thanks
You can use JSON as #CommonsWare points out to store your data in SharedPreferences. I have such an answer that using GSON here:
https://stackoverflow.com/a/5968562/617044
Though not ideal, if you want to use Preferences only, You can store String in preferences. When next value is to be added, retrive the old one add 'comma' and new value.
Whenever you want to use these values, use StringTokeniser. Tokenise elements by 'comma' character.

Maximum Size of SharedPreferences class

I want to save a lot of strings with SharedPreferences class .
These strings are quit long.
I really want to know the maximum length of a string that can be save in shared preferences in android.And Also How much size of data i can store in This SharedPrefernces class.
As per android architecture there is no such limit to store data in SharedPreference. Better way is to database (SQLite) when you have to deal with huge amount of data
I read somewhere that there is no hard limit other than Integer.MAX_VALUE ( maximal string length). But it is not advisable to store that much on shared preferences, as this is XML file which must be parsed and you will have a problems while parsing it.
I used to store about 50-100KBytes there. It worked.
The exact answer obtained manually is: maximum Unicode symbol's size is 5657632 symbols (or from [0 to 5657631]) in my case. It's some about 2.7MB for SharedPReference.Editor .
Rather large storage.
You ca use this size twice:
PreferenceManager.getDefaultSharedPreferences(c)
context.getSharedPreferences("<key>", <Mode>);
Of course is't limit for SharedPreferences but if system won't have enough memory it is one first stuff what DELETE it, you remember it.

Categories

Resources