Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Shared Preferences in Android with Examples

In Android, SharedPreferences is a framework API that allows you to store and retrieve small sets of data as key-value pairs. It's suitable for scenarios like saving user preferences, storing simple configuration settings, or persisting lightweight data across app restarts.

Here's a guide on how to use SharedPreferences:

Storing Data in SharedPreferences

  1. Obtain an instance of SharedPreferences: You can access SharedPreferences via getSharedPreferences(name, mode) method of a Context:

    val sharedPref = context.getSharedPreferences(
        "my_preferences",
        Context.MODE_PRIVATE
    )
    

    Alternatively, if you are using an activity, you can use the PreferenceManager:

    // This method is deprecated in newer versions of AndroidX Preference library
    val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)
    
  2. Store data: Data can be stored using the SharedPreferences.Editor:

    with(sharedPref.edit()) {
        putString("username", "JohnDoe")
        putInt("user_age", 30)
        apply()  // or use commit() to save synchronously
    }
    

Retrieving Data from SharedPreferences

  1. Obtain an instance of SharedPreferences (as shown above).

  2. Retrieve data:

    val username = sharedPref.getString("username", "defaultUsername")
    val userAge = sharedPref.getInt("user_age", -1)
    

    In the above code, "defaultUsername" and -1 are default values that will be returned if the keys don't exist.

Deleting Data from SharedPreferences

  1. Obtain an instance of SharedPreferences (as shown above).

  2. Remove specific data:

    with(sharedPref.edit()) {
        remove("username")
        apply()
    }
    
  3. Clear all data:

    with(sharedPref.edit()) {
        clear()
        apply()
    }
    

Considerations:

  1. Private Data: By default, the file containing the shared preferences is set to private, so only your app can access it. However, there are other modes available which might make the file accessible to other apps, so always be careful when choosing a mode.

  2. Performance: SharedPreferences are stored in XML format. Therefore, it's best suited for small datasets. If you need to store a large amount of structured data, consider using an SQLite database or another persistence solution.

  3. Data Types: SharedPreferences supports storing boolean, float, int, long, and string data types.

  4. Commit vs. Apply: The commit() method saves the changes synchronously and returns a boolean indicating the success or failure of the save operation. The apply() method saves the changes asynchronously without notifying you of the outcome.

  5. Thread Safety: SharedPreferences is thread-safe, but if you're modifying the shared preferences concurrently in multiple threads, it's good practice to synchronize the operations.

Using SharedPreferences effectively can help you manage small sets of data efficiently without the need for complex storage solutions. However, always be mindful of the amount and type of data you store, as there are better-suited solutions for different scenarios.

  1. Working with Shared Preferences in Android example code:

    • Description: Introduces the concept of Shared Preferences for lightweight data storage.
    • Example Code (Java/Kotlin):
      // Storing data in Shared Preferences
      SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("key", "value");
      editor.apply();
      
      // Retrieving data from Shared Preferences
      String retrievedValue = preferences.getString("key", "default");
      
  2. Storing and retrieving data using Shared Preferences:

    • Description: Demonstrates the basic process of storing and retrieving data using Shared Preferences.
    • Example Code (Java/Kotlin):
      // Storing data
      SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("username", "John Doe");
      editor.putInt("score", 100);
      editor.apply();
      
      // Retrieving data
      String username = preferences.getString("username", "Default User");
      int score = preferences.getInt("score", 0);
      
  3. Customizing Shared Preferences in Android:

    • Description: Explores customizing Shared Preferences for specific use cases or preferences.
    • Example Code (Java/Kotlin):
      // Customizing Shared Preferences with a custom name and mode
      SharedPreferences customPreferences = getSharedPreferences("CustomPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor customEditor = customPreferences.edit();
      customEditor.putString("key", "value");
      customEditor.apply();
      
  4. Shared Preferences vs SQLite in Android:

    • Description: Compares Shared Preferences and SQLite for data storage based on use cases and requirements.
    • Example Code (Java/Kotlin):
      // Using SQLite for more complex data storage
      
  5. Handling complex data in Shared Preferences Android:

    • Description: Shows how to handle complex data types such as JSON objects or arrays in Shared Preferences.
    • Example Code (Java/Kotlin):
      // Storing and retrieving a JSON object in Shared Preferences
      
  6. Using Shared Preferences for user settings in Android:

    • Description: Illustrates using Shared Preferences to store and retrieve user settings.
    • Example Code (Java/Kotlin):
      // Storing and retrieving user settings
      
  7. Securely storing data in Shared Preferences Android:

    • Description: Discusses techniques for secure data storage in Shared Preferences.
    • Example Code (Java/Kotlin):
      // Using encryption or other security measures for data in Shared Preferences
      
  8. Shared Preferences and data persistence in Android:

    • Description: Explores the role of Shared Preferences in data persistence across app sessions.
    • Example Code (Java/Kotlin):
      // Ensuring data persistence using Shared Preferences
      
  9. Managing SharedPreferences keys and values in Android:

    • Description: Discusses best practices for managing keys and values in Shared Preferences.
    • Example Code (Java/Kotlin):
      // Defining constants for Shared Preferences keys
      public class AppPreferences {
          public static final String KEY_USERNAME = "username";
          // ...
      }
      
      // Usage
      SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString(AppPreferences.KEY_USERNAME, "John Doe");
      editor.apply();
      
  10. SharedPreferences in Android with Kotlin examples:

    • Description: Demonstrates the usage of Shared Preferences in Android using Kotlin.
    • Example Code (Kotlin):
      // Storing data in Shared Preferences with Kotlin
      val preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
      val editor = preferences.edit()
      editor.putString("key", "value")
      editor.apply()
      
      // Retrieving data from Shared Preferences with Kotlin
      val retrievedValue = preferences.getString("key", "default")
      
  11. SharedPreferences and SharedPreferences.Editor in Android:

    • Description: Shows the use of SharedPreferences and SharedPreferences.Editor for data storage and modification.
    • Example Code (Java/Kotlin):
      // Working with SharedPreferences.Editor
      SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      
      // Modifying data
      editor.putString("key", "new value");
      editor.apply();
      
  12. Clearing SharedPreferences in Android:

    • Description: Demonstrates how to clear all data from Shared Preferences.
    • Example Code (Java/Kotlin):
      // Clearing all data in Shared Preferences
      SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.clear();
      editor.apply();
      
  13. SharedPreferences and app upgrades in Android:

    • Description: Discusses considerations for handling data in Shared Preferences during app upgrades.
    • Example Code (Java/Kotlin):
      // Handling Shared Preferences during app upgrades