I am pretty new to Android dev. I am browsing through the API here http://developer.android.com/reference/android/content/SharedPreferences.html
but I am confused about how to actually get the file contents and read or write from them.
I have this code to get the SharedPreferences object:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( MyClassName.this);
but in this case, I get the reference to sharedPreferences, but not a connection to my file which stores the preferences data.
Maybe I am not understanding the API correctly, but how am I supposed to get the reference to the file and read/write to it?
Thanks!
If you want to get values from your SharedPreferneces you have to use (this example works with Strings, but you can also call getBoolean, getInt, etc..)
prefs.getString("myString", "defaultValue"); // "defaultValue" will be returned in case "myString" wasn't saved on the SharedPreferences
to store some values you can do it like this:
prefs.edit()
.putString("myString", "newValue")
.putBoolean("working", true)
.commit();
As you can see you can edit more than one value at once..
edit() will return you an editor that you have to use in order to modify the sharedpreferences file, and when you end to edit it call commit() in order to make the changes permanently
but in this case, I get the reference to sharedPreferences, but not a connection to my file which stores the preferences data.
The SharedPreferences object has a "connection" to the file which stores the preference data.
Maybe I am not understanding the API correctly, but how am I supposed to get the reference to the file and read/write to it?
To read preferences, use the getters on SharedPreferences (e.g., getString()). To write preferences yourself:
Get a SharedPreferences.Editor by calling edit() on the SharedPreferences object
Use the setters on the Editor (e.g., putString())
Call apply() (where possible) or commit() on the Editor to save your changes
In addition, you can (and in many cases should) also use a PreferenceActivity to allow users to directly view and modify their preferences.
Related
How can I make data available through my whole android app?
For instance, I want to display a user picture in the toolbar in every screen. Also, the name of the user is displayed in the navigation drawer in every screen.
Is a singleton the right approach for this? Or are other techniques better?
I have been googling a lot, but i can't find a good approach for my use case so far.
To use shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
to save in shared preferences:
editor.putString("tag", "save me please");
editor.apply();
to retrieve from shared preferences:
String s = preferences.getString("tag", "default_value");
Notes:
You can make your tags as string constants to make sure you are always using the same value.
If you use the editor for multiple values, always remember to add editor.apply() in the end, to actually apply your changes.
If you want the editor to write the changes synchronously, use editor.commit() instead. You can save any type of variable in the shared preferences, just use the appropriate method (instead of putString use putInt, putLong, etc - same with the getSring). More on Shared Preferences in the API here
I'm having problems to decide if I should use apply() or commit() from SharedPreferences.Editor
Since apply() is async, and we are going to read right after write, it's safer to use commit(). On the other hand, this method might block the UI thread for far too long. I don't want to use local variables because I want to read other settings, and since I don't know where sendData() will be called, the mix of reading through setting and local variables will add unnecessary complexity.
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Apply the edits!
editor.apply();
// Read data of SharedPreferences (including other previously data)
// and send to web service
sendData();
Above is a code snippet of something similar I want to do. I want to make sure that when I read any data from SharedPreferences, all settings were committed.
Since you dont know and when does sendData() will be called then you have no choice but to use commit instead of apply that it will give you the previously added data when you read and send it to the external server, but apply wont if it is still putting the data to the disk but you already read the data which will give you inconsistent result that it is executed asynchronously.
There is one way to know that data is stored, through using listener registerOnSharedPreferenceChangeListener in the SharedPreferences this will only work if you always know the last added data to the disk before you read it.
I'm novice in Android development and now I'd really like to learn Shared Preferences. I've googled it so many times and I don't think I quite mastered it.
I believe this Shared Preferences will help me to store username and a password on my login screen activity. Thanks you!
I made some videos about this as an audition for a job. They helped me get the job, and they're still available on Vimeo, so hopefully they can help you out.
Part 1: Saving Data
Part 2: Retrieving Data
Also, for what it's worth, be careful storing usernames and passwords in SharedPreferences. You can do it there, but read up on the risks in this other SO question: What is the most appropriate way to store user settings in Android application
For android, there are primarly three basic ways of persisting data:
shared preferences to save small chunks of data
tradition file systems
a relational database management system through the support of SQLite databases
SharedPreferences object help you save simple application data as a name/value pairs - you specify a name for the data you want to save, and then both it and its value will be saved automatically to an XML file for you. To save a data in sharedPreferences file:
Obtain an instance of sharedPreferences file:
SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);
Create SharedPreferences.Editor object
To put for example a String value into SharedPreferences object use putString() method.
To save the changes to the preferences file, use the commit() method
That will look like this:
// obtain an instance of the SharedPreferences class
preferences = getSharedPreferences(prefFileName, MODE_PRIVATE);
editor = preferences.edit();
// save username String
editor.putString("username", student).commit();
To retrieve it use getString() method:
preferences.getString(username, null) where null is a default value that will be returned if username key is not found in the file.
I want to save some values before i closed the app. But i don't know if i must create a new file(.txt) and save it in; or i just can change strings.xml file and when i open app next time the saved values will be the right saved values or will be walues which i define them before first using. I know that exist really easy way to read from strings.xml file and so i think that there must be a way to set values in this file before closing (but i can't find on the net). Thanks for any examples or yours advice and explanation.
Android provides the SharedPreferences class to help you save simple application data.
You can use SharedPreferences class to save the config information or anything you want.
When you put the application in background or close it, onStop() will be called. You can override it to implement what you want.
Usage of SharedPreferences class is very simple:
step 1: Writing with SharedPreferences object
//Create a object SharedPreferences from getSharedPreferences("name_file",MODE_PRIVATE) of Context
private SharedPreferences pref;
pref = getSharedPreferences("info", MODE_PRIVATE);
//Using putXXX - with XXX is type data you want to write like: putString, putInt... from Editor object
Editor editor = pref.edit();
editor.putString("key5","value5");
//finally, when you are done saving the values, call the commit() method.
editor.commit()
step2: Reading with SharedPreferences object
//get SharedPreferences from getSharedPreferences("name_file", MODE_PRIVATE)
SharedPreferences shared = getSharedPreferences("info",MODE_PRIVATE)
//Using getXXX- with XX is type date you wrote to file "name_file"
String string_temp = shared.getString("key5");
The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the application that created it.
The shared preferences file is save as an XML file in /data/data/<package_name>/shared_prefs folder
Do your save operation in your activity's overridden onStop() method.
As for where/how to save: follow the example here :
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can do it using preferences. Check this tutorial and example
http://www.vogella.com/articles/Android/article.html#preferences
If data has to be shared between multiple activities then use Shared Preferences
Better go with shared preference for saving data but if you think you have save more amount of data then better go with database or save it as file.
Refer this LINK
In my app, I use a PreferenceActivity framework to store persistent data. My intent is to create multiple save files, all of which may be accessed by the Preferences, but only one at a time.
When is it better to use a private file generated by Context.openFileOutput() and when is it better to use SharedPreferences?
EDIT
My data exists solely in primitives.
Normally developers use a preference file that is common to an entire app using getDefaultSharedPreferences.
However, Android has a getSharedPreferences(String name, int mode) method in Context. You could use this to have multiple preference files, in your case - save files, by using unique names passed into the name parameter.
Regarding volatility, you can force the preferences to save by getting an Editor via edit() and then calling commit().
Make sure to note that the SharedPreferences will indeed be shared based on the name:
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.