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!
Related
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.
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.
How do I save an integer that can be overwritten and then read it on android? I am using libgdx. I know how to do it for my desktop, but I want internal storage.
You should use libgdx Preferences.
That way it will work cross-plattform! (including Android)
Since you just want to store some Integer that should be just what you need.
See example:
//get a preferences instance
Preferences prefs = Gdx.app.getPreferences("My Preferences");
//put some Integer
prefs.putInteger("score", 99);
//persist preferences
prefs.flush();
//get Integer from preferences, 0 is the default value.
prefs.getInteger("score", 0);
There are different ways to do that:
You can write to a FileHandle. Just create a FileHandle like Gdx.files.local("myfile.txt"); and write to it using fileHandle.writeString(Integer.toString(myInt));
Note, that Internal and Classpath are read-only, so you can't write files there.
Also note, that not all types of the gdx.files. are usable for all backends. More on that here.
The second way to do that are the Preferences. The Preferences are the only way to have persistent data for HTML5 applications.
The Preferences are XML files in which you can store, read and change data.
To create Preferences for your app you just need to call:
Preferences myPref = Gdx.app.getPreferences("PreferenceName");
Note, that you should use the full name, for example com.stackoverflow.preferences, as on desktop all Preferences use the same file.
To write data you can use myPref.putInteger("name", value) for Integers, myPref.putBoolean(("name", value) for Booleans... Make sure you call myPref.flush() after all changes, to save the new data.
To get the data you can call myPref.getInteger("name, defaultValue"). The default value is returned if there is no data with the given name.
More on Preferences here.
Hope i could help.
i am new to android, i searched a lot and couldn't find a satisfying answer; what i need is to save some setting for my application such as
1> language, number of items to display, display/not display images, etc...
which i think is best done using the shared preferences
2> save which data categories to get from the internet...
here is my problem:
i have data divided into category objects with key, name, type, data[]...(data[] is changing all the time and not saved after exiting the application),(key, name, type are final values defined by programmer).
and because there are many categories which the user may or may not want to load(around 25), he/she can choose which categories to display, and these choices must be saved.
i think using shared preferences will not help because of the complexity of the data; i was thinking of using sqlite or xml, not sure which is the best choice keeping in mind efficiency and memory size.
note: i am using a global variable for the category information array, that is because data[] needs to be refreshed automatically every 2-3 minutes and must be available to all activities also efficiency and memory space are an issue.
i will appreciate any advice, thank you in advance.
1> SharedPreferences is the right choice
2> you have multiple possibilities
a) Use the internal storage and use Object Serialization (for simplicity reasons), xml (if you want to exchange the data) or use a own format
b) SQLite is the fastest solution. But you have to do more programming for that
b would be my choice, so create a DB-Object (static or singleton pattern) and write functions for every database task
1) Yes, SharedSettings should help youy. There is plenty information around, but post back if you are lost.
2) I would make a table with all the categories and a boolean value thats says "show" where you can keep if the user wants to show it or not.
Of course it depends on the size of the categories and how much they change, because otherwise you will be updating the database forever.
User shared preference in store your setting,
SharedPreferences sharedPreferences = this.applicationContext.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
//For saving the setting:
//for storing long
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
//for storing string editor.commit();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
//and similarly for int,float etc
//For Retrieving the string:
sharedPreferences.getLong(key, defaultValue); //for long value
sharedPreferences.getSting(key, defaultValue); //for string value
I've been looking for over the past day and a half at several websites about how to store strings/string arrays/etc. and I can't seem to figure it out. I'm not sure if I'm just not quite comprehending how to implement data storage..or what. But here is my problem, simply put, I have two activity pages (we'll name 'A,B' respectively) . All I want to do is get a string from a text view in Activity B, store it in an array, and then have it accessed by clicking a button in Activity A.
I know it is simple, but I hit a block for some reason... I am trying to use SharedPreferences but how would I obtain the string from Activity B, store it in a global array, and let it be accessed by a different activity (Activity A) ?
Just store it into shared preferences (usually in onPause()):
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString(GAME_STATE, writer.toString());
editor.commit();
in one activity and load in another (usually in onResume()):
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String jsonState = preferences.getString(GAME_STATE, null);
And nothing prevents you from using public static variables
You can't store an array directly in shared preferences, but you can store a set.
See putStringSet and getStringSet. You can add all the items from your array to a LinkedHashSet (as long as they are unique) if you wish to store them in SharedPreferences. See Konstantin's answer for the general idea on how to use SharedPreferences.
Yes you can obtain and store value in global array but you will loss everything once you close the application. So its better you create a table and store/get values from the table whenever you required.
Here is an example for creating SQLite example.