If you want to store information/data at the application level then it can be achieved using Shared Preferences. The data that you store using Shared Preferences will persist even after relaunch and reboot.
Note: If the user goes to Setting->Application setting->Application and Clears the data (Clear data option) for you app then all the data stored will be deleted.
How to use SharePreferences
Data is scored as Key-Value Pairs using SharedPreferences APIs.
There are two ways (methods) in which you can use SharedPreferences.
This method should be used if your application needs only one shared preference file for your activity. This uses a default shared preference file and hence there is no need to specify the file name for it.
SharedPreferences mySharedPreference = getActivity().getPreferences(Context.MODE_PRIVATE);
You need to have the application Context object in order to access/call shared preferences,
Example : Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( "com.code2care.sharedPreferences.pref_file_key", Context.MODE_PRIVATE);
You may use this method if you need more than one shared preference file. getSharedPreferences() signature has two parameters 1st one specifies the shared preference file names and the second parameter specifies how the file would be accessed. Note that the shared preference file name should uniquely identify your app and must be specified as "com.companyname.appname.pref_file_name"
SharePreferences File Access Modes
You can use the following modes to create or access SharePreferences file,
This is a default file creation mode. When this mode has used the file created can be accessed only by the application that creates it. It has a constant value 0.
Definition : public static final int MODE_PRIVATE = 0
This file creation mode is used when the file already exists and data is to be written to the existing file at the end of the file.
This is a database open flag, when it is set the database is opened with write-ahead logging enabled mode.
4. MODE_WORLD_READABLEThis mode is used when you want the file to be readable by all other applications. It has a Constant value 1 Note: MODE_WORLD_READABLE is deprecated as on API level 17 as it is very dangerous and likely to cause security loopholes in your applications. So it should not be used.
5. MODE_WORLD_WRITEABLEThis mode is used when you want the file to be writable by all other applications. It has a Constant value 2 Note: MODE_WORLD_WRITEABLE is deprecated as on API level 17 as it is very dangerous and likely to cause security loopholes in your applications. Its use is strongly discouraged.
Writing to a Shared Preference file
We have till now seen how we can create a shared preference file for your Android application. Now let's see how we can write data to this file.
In order to write to the shared preference file we need to use Editor Interface. The Editor interface is used to modify contents of a shared preference file.
Let's see all the methods of Editor Interface.
1. putBoolean(String key, boolean value)
This method is used when you want to set a boolean value to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called.
2. putFloat(String key, float value)
This method is used when you want to set a float value to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called.
3. putInt(String key, int value)This method is used when you want to set an Int value to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called.
4. putLong(String key, long value)
This method is used when you want to set a long value to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called.
5. putString(String key, String value)
This method is used when you want to set a String value to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called. Note that setting value as null is the same as calling remove(String) with the key specified).
6. putStringSet(String key, Set values)
This method is used when you want to set a String Set values to a preference editor. This key-value will be written to the SharedPreference once commit() or apply() method is called. Note that setting value as null is the same as calling remove(String) with the key specified).
It is used to commit changes that you have made from the Editor back to the SharedPreferences object after being edited. The current value of the SharedPreferences is automatically modified and replaced.
If you used this method, it will remove all values from the SharedPreferences.
9. commit()Commits changes from the Editor to the SharedPreference Object. It returns a boolean true value if the commit was successful.
Now let's see how to create a SharedPreferences object and access it using Editor and write a string value back to it.
Example : SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); Editor sPrefEditor = sharedPref.edit(); sPrefEditor.putString("message", "Hello there!"); sPrefEditor.commit();
Note: The changes that we make in an editor are batched, and are not copied back to the original SharedPreferences unless commit() or apply() is called.
Reading data from SharePreferences Object
Till now we have seen how to create a SharePreferences file and write to it. Now let's see how we can access what we write to SharePreferences.
To read from shared preference object we use getResources() method with getnteger(), getString(), getFloat() e.t.c methods with the key of the value that you want to access.
Example : SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); String msg = getResources().getString("message");
- Android : Execute some code after back button is pressed
- Android is starting optimizing... app 1 of 1
- How to change Android Button Color using xml attribute and programatically using java
- SQLite with Android Easy to Understand Tutorial that covers Select, Insert, Update and Delete
- How to make Android EditText not editable
- Make Android TextView Clickable like Buttons
- Unable to establish connection to adb : Android Studio Error
- Android Constant and Resource Type Mismatches Lint
- Android Shared Preferences API tutorial
- Fixing Android unknown error 961 while downloading app
- DDMS files not found hprof-conv.exe
- How to reset eclipse layout
- Android Developers Bluetooth Tutorial
- Android Studio Native typeface cannot be made error
- 21 Useful Android Emulator Short-cut Keyboard Keys
- Multiline EditText in Android Example
- How to screenshot on Android?
- Unable to load VM from snapshot. The snapshot has been saved for a different hardware configuration
- How To Disable Landscape Mode in Android Application
- Change Title text for Android Activity using java code
- Android : Class file collision: A resource exists with a different case
- Android Emulator Soft Back button action using Computer keyboard
- Device not compatible error Android Google Play Store
- ERROR x86 emulation currently requires hardware acceleration. Intel HAXM is not installed on this machine
- java.lang.NoClassDefFoundError android.support.v4.content.LocalBroadcastManager
- Disable Fading Edges Scroll Effect Android Views
- Android : Unable to load VM from snapshot : Mac OS X Error
- Change Android EditText Cursor Height
- What is Android Toast.LENGTH_SHORT and Toast. LENGTH_LONG durations
- How to add border to Android TextView
- Remove ActionBar from Activity that extends appcompat-v7
- How to send SMS on Android Emulator
- Android RatingBar Example
- This Toast was not created with Toast.makeText() : Android RuntimeException
- Android Studio Ctrl Shift o auto import not working
- Android : Duplicate registration for activity com.example.abc
- ADT Installation Error: requires plug-in org.eclipse.wst.sse.ui
- Running Android Lint has encountered a problem NullPointerException Error
- Android Emulator] ##KBD: Full queue, lose event Error Logs
- Export aborted because fatal lint error were found
- Android Parsing Data for android-L failed Unsupported major.minor version 51.0 Error
- Android : Accidental Octal Lint Warning
- Android ListView turns Black or Flickers while Scrolling
- How to make a dummy phone call from Android Emulator device
- Add scroll to div element in HTML Css - CSS
- Officially Send WhatsApp message using webpage (html) - WhatsApp
- Calculate Volume of Cone - C-Program
- Install Cygwin on Windows PC to learn Objective-C - Objective-C
- Spell check not working in Gmail : Mac OS X - Mac-OS-X
- [Soluiton] You already have the latest version of Android Studio installed - Android
- How to change Chrome Spell Check from UK English to US English - Chrome
- How to See Hidden Folders and Files on Mac OS X - Mac-OS-X
- Safari appends .html extension to files that are downloaded - Mac-OS-X
- Sharepoint errors were found when compiling the workflow - SharePoint
- Chessboard with pieces using pure HTML and CSS - Html
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server - Java
- bash: command not found error on macOS Terminal, Linux, Unix or Windows - MacOS
- Android Studio Change SDK Path - Android