In my application,there are some application specific settings, which should be available to me , next time when my application starts up.
In other words i want the data to be available across the sessions of an application cycle.
Can this be achieved without using database(sqlite).
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the
getSharedPreferencesmethod of theContextclass. The preferences are stored in a file, that can be either a custom one (1) or the default file (2).(1) Here is how you get the instance when you want to specify the file name
MODE_PRIVATEis the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported areMODE_WORLD_READABLEandMODE_WORLD_WRITEABLE. InMODE_WORLD_READABLEother application can read the created file but can not modify it. In case ofMODE_WORLD_WRITEABLEother applications also have write permissions for the created file.(2) The recommended way is to use by the default mode, without specifying the file name:
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
To store values in the preference file
SharedPreference.Editorobject has to be used.Editoris the nested interface of theSharedPreferenceclass.Editor also support methods like
remove()andclear()to delete the preference value from the file.Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of
getPreferences()method of the activity. ThegetPreferencemethod uses thegetSharedPreferences()method with the name of the activity class for the preference file name.Following is the code to get preferences:
The code to store values is also same as in case of shared preferences.
You can also use other methods like storing the activity state in database. Note Android also contains a package called
android.preference. The package defines classes to implement application preferences UI.To see some more examples check Android’s Data Storage post on developers site.