Software Development Exam  >  Software Development Notes  >  Shared Preferences in Android with Examples

Shared Preferences in Android with Examples - Software Development PDF Download

  • Shared Preferences in Android with Example

    • Last Updated: 09 Feb, 2023

    • Shared Preferences in Android offer a convenient method for storing and retrieving small amounts of data as key/value pairs.
    • These key/value pairs can consist of various primitive data types like String, int, float, and Boolean, forming preferences stored in an XML file on the device.
    • Think of Shared Preferences as a dictionary where each key represents a specific data point, such as a username, with the corresponding value stored alongside it.
    • The Shared Preferences class in Android provides essential APIs for managing this data, enabling effortless reading and writing operations.
    • Utilizing Shared Preferences involves a simple API for storing preferences and accessing them whenever necessary.
  • Android Shared Preferences Java and Kotlin Programming Language for Android

  • Shared Preferences Usage
    • Shared Preferences serve various purposes, such as preserving user settings or storing data accessible across different activities within an application.
    • For persistent data storage, it is recommended to save information during the onPause() lifecycle method and restore it in the onCreate() method of an activity.
    • Data stored via Shared Preferences remains private and specific to the application, distinct from the instance state of the activity.
  • Shared Preferences in Android with Examples - Software Development

How are Shared Preferences different from Saved Instance State?

  • Shared Preferences
  • Saved Instance State

Saved Instance State

Persist Data across user sessions, even if the app is killed and restarted, or the device is rebooted

Preserves state data across activity instances in the same user session.

Data that should be remembered across sessions, such as the user's preferred settings or game score.

Data that should not be remembered across sessions, such as the currently selected tab or current state of activity.

A common use is to store user preferences

A common use is to recreate the state after the device has been rotated

How to Create Shared Preferences?

  • The first thing we need to do is to create one shared preferences file per app. So name it with the package name of your app- unique and easy to associate with the app. When you want to get the values, call the getSharedPreferences() method. Shared Preferences provide modes of storing the data (private mode and public mode). It is for backward compatibility- use only MODE_PRIVATE to be secure.
  • getSharedPreferences()
  • MODE_PRIVATE
  • SharedPreference(SP) file
  • context mode
  • MODE_PUBLIC will make the file public which could be accessible by other applications on the device
  • MODE_PRIVATE keeps the files private and secures the user's data.
  • MODE_APPEND is used while reading the data from the SP file.

Nested classes of Shared Preferences

Nested classes of Shared Preferences
  • SharedPreferences.Editor: This interface is utilized for writing (editing) data in the Shared Preferences (SP) file. After editing, one must commit() or apply() the changes to the file.
  • SharedPreferences.Editorcommit()apply()
  • SharedPreferences.OnSharedPreferenceChangeListener(): This function is triggered when a shared preference is altered, added, or deleted. It can even be called if a preference retains its existing value. This callback operates on the main thread.
  • SharedPreferences.OnSharedPreferenceChangeListener()

    Following are the methods of Shared Preferences

    Following are the methods of Shared Preferences
  • contains(String key): This function is employed to verify if the preferences hold a specific preference.
  • contains(String key)
  • edit(): This method is utilized to create a new Editor for these preferences. Through this Editor, modifications can be made to the data in the preferences and these changes can be atomically committed back to the SharedPreferences object.
  • edit()
  • getAll(): This method is employed to retrieve all values from the preferences.
  • getAll()
  • getBoolean(String key, boolean defValue): Used to fetch a boolean value from the preferences.
  • getBoolean(String key, boolean defValue)
  • getFloat(String key, float defValue): This method retrieves a float value from the preferences.
  • getFloat(String key, float defValue)
  • getInt(String key, int defValue): Retrieves an integer value from the preferences.
  • getInt(String key, int defValue)
  • getLong(String key, long defValue): Retrieves a long value from the preferences.
  • getLong(String key, long defValue)
  • getString(String key, String defValue): Retrieves a string value from the preferences.
  • getString(String key, String defValue)
  • getStringSet(String key, Set defValues): Retrieves a set of string values from the preferences.
  • getStringSet(String key, Set defValues)
  • registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener): Used to register a callback that is invoked when a preference changes.
  • registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)
  • unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener): Unregisters a previously set callback.
  • unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)Following is a sample byte code demonstrating how to write Data in Shared Preferences:Following is the sample byte code showing how to read Data in Shared Preferences:

    Example to Demonstrate the use of Shared Preferences in Android

    • Shared Preferences in Android allow you to store private primitive data in key-value pairs.
    • In the provided example, there are two EditText fields that retain the data entered by the user.
    • This functionality is commonly used in applications featuring forms to enhance user experience.

    Implementation in activity_main.xml

    Below is the code snippet that illustrates the UI implementation:

    • activity_main.xml

    Below is the code for the MainActivity file. Comments are included within the code for better understanding.

    Main Activity

    • Java
    • Kotlin

    Explanation:

    • The MainActivity class is a crucial component in Android development.
    • Java and Kotlin are popular programming languages used for Android app development.

    Code Snippet Example

    Explanation:

    import androidx.appcompat.app.AppCompatActivity;android.content.SharedPreferences;android.os.Bundle;android.widget.EditText;
    • The code snippet demonstrates how to work with SharedPreferences in Android.
    • SharedPreferences are used to store and retrieve key-value pairs of primitive data types.
    • The code includes methods to fetch and store data when the app is paused and resumed.

    MainActivity Class

    Explanation:

    • The MainActivity class extends AppCompatActivity, which is a base class for activities.
    • It includes EditText fields to capture user input for name and age.
    • Data fetching from SharedPreferences is done in the onResume() method.
    • Data storing in SharedPreferences is done in the onPause() method.

    Android Activity Lifecycle

    • The Android Activity Lifecycle consists of various methods that are called at different stages of an activity's life.
    • onCreate(): This method is called when the activity is first created. It is typically used for initial setup.
    • onResume(): Called when the activity will start interacting with the user. This is a good place to begin animations, music playback, etc.
    • onPause(): Invoked when the activity is going into the background but has not been destroyed. This is a good place to save data that should be persistent.

    Shared Preferences in Android

    • Shared Preferences is a way in Android to store primitive data types in key-value pairs.
    • It allows you to store small amounts of data that persist even after the user closes the application.
    • Example: Storing user settings like user preferences, high scores in a game, etc.
    android.os.Bundleandroid.widget.EditTextandroidx.appcompat.app.AppCompatActivity

    Summary of Information

    • Video Player
      • 00:00
      • 00:35
      • Use Up/Down Arrow keys to increase or decrease volume.
    • Please Login to comment...
      • Login
      • Like

    Paraphrased Explanation

    • Video Player:
      • This feature allows users to play videos on the platform.
      • The timestamps 00:00 and 00:35 indicate the start and end points of the video.
      • Instructions are provided to adjust the volume using the Up/Down Arrow keys.
    • Please Login to comment...:
      • Users are required to log in to leave comments on the platform.
      • There is an option to 'Like' content available for logged-in users.
    The document Shared Preferences in Android with Examples - Software Development is a part of Software Development category.
    All you need of Software Development at this link: Software Development
    Download as PDF

    Top Courses for Software Development

    Related Searches

    mock tests for examination

    ,

    Extra Questions

    ,

    Exam

    ,

    Free

    ,

    pdf

    ,

    study material

    ,

    Important questions

    ,

    practice quizzes

    ,

    Shared Preferences in Android with Examples - Software Development

    ,

    MCQs

    ,

    past year papers

    ,

    Viva Questions

    ,

    Semester Notes

    ,

    video lectures

    ,

    Previous Year Questions with Solutions

    ,

    Sample Paper

    ,

    shortcuts and tricks

    ,

    ppt

    ,

    Shared Preferences in Android with Examples - Software Development

    ,

    Objective type Questions

    ,

    Summary

    ,

    Shared Preferences in Android with Examples - Software Development

    ;