ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 1
    COMP4124
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    COMP4124›User Preferences
    Mobile Application Development 1Topic 17 of 33

    User Preferences

    5 minread
    923words
    Intermediatelevel

    User Preferences in Android

    In Android, User Preferences allow you to store and retrieve small amounts of data, such as settings or user choices, across sessions. This data is typically stored in a simple key-value pair format and can be used to persist data like app settings, user preferences, and application configurations, even when the app is closed or the device is rebooted.

    Android provides several ways to handle user preferences, but the most common and easiest method is through SharedPreferences. Other options include using databases, files, or cloud storage, but SharedPreferences is best for lightweight data storage.


    1. What is SharedPreferences?

    SharedPreferences is an interface in Android used for reading and writing simple key-value pairs of primitive data types (like String, int, boolean, etc.). It is ideal for storing settings or preferences that should persist even when the app is closed.

    2. How to Use SharedPreferences

    Here’s how you can use SharedPreferences to save and retrieve user preferences in Android:


    A. Saving Preferences

    To save data in SharedPreferences, you need to:

    1. Get a reference to the SharedPreferences object.
    2. Use an Editor to put data into SharedPreferences.
    3. Commit or apply the changes.

    Example:

    // 1. Get SharedPreferences object
    SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
    
    // 2. Get the Editor object
    SharedPreferences.Editor editor = sharedPreferences.edit();
    
    // 3. Put data into SharedPreferences
    editor.putString("username", "john_doe");  // Save String data
    editor.putInt("user_age", 25);  // Save integer data
    editor.putBoolean("is_logged_in", true);  // Save boolean data
    
    // 4. Commit or apply the changes
    editor.apply();  // Apply is asynchronous, commit is synchronous
    
    • getSharedPreferences(String name, int mode): Gets the SharedPreferences object. The name is the name of the preferences file, and mode defines the file access mode.
    • SharedPreferences.Editor: An editor for modifying SharedPreferences data.
    • apply(): Asynchronously saves the changes (recommended for performance).
    • commit(): Synchronously saves the changes (slower than apply()).

    B. Retrieving Preferences

    Once you've saved data in SharedPreferences, you can retrieve it using the get methods, which allow you to specify the key and a default value in case the key doesn't exist.

    Example:

    // Get SharedPreferences object
    SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
    
    // Retrieve data
    String username = sharedPreferences.getString("username", "default_name");  // Default value is used if key doesn't exist
    int userAge = sharedPreferences.getInt("user_age", 0);  // Default is 0
    boolean isLoggedIn = sharedPreferences.getBoolean("is_logged_in", false);  // Default is false
    
    • getString(String key, String defaultValue): Retrieves a String value.
    • getInt(String key, int defaultValue): Retrieves an int value.
    • getBoolean(String key, boolean defaultValue): Retrieves a boolean value.

    C. Removing Preferences

    If you want to delete a specific preference, you can use the remove() method in the Editor.

    Example:

    SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    
    // Remove a specific preference
    editor.remove("username");
    editor.apply();
    

    You can also clear all preferences using clear():

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();  // Clears all stored preferences
    editor.apply();
    

    3. Preferences for Different Purposes

    You can store different types of data in SharedPreferences, but it's most commonly used for:

    • User Settings: Language preferences, theme preferences, etc.
    • Login States: Storing login information or a flag indicating whether the user is logged in.
    • App Configurations: Custom app behavior or settings (like enabling/disabling certain features).
    • Flags or Booleans: To track whether the user has completed a certain action (e.g., first launch, tutorial completion).

    4. Example: Storing and Retrieving User Preferences for Theme

    Let’s say you want to let the user choose between a light and dark theme for your app. You can store the user’s theme preference using SharedPreferences.

    A. Save Theme Preference:

    SharedPreferences sharedPreferences = getSharedPreferences("AppSettings", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("dark_theme", true);  // User chose dark theme
    editor.apply();
    

    B. Retrieve Theme Preference and Apply:

    SharedPreferences sharedPreferences = getSharedPreferences("AppSettings", MODE_PRIVATE);
    boolean isDarkTheme = sharedPreferences.getBoolean("dark_theme", false);  // Default is false
    
    if (isDarkTheme) {
        // Apply dark theme
        setTheme(R.style.AppTheme_Dark);
    } else {
        // Apply light theme
        setTheme(R.style.AppTheme_Light);
    }
    

    In this example:

    • You’re saving a boolean value (dark_theme) that indicates whether the user prefers a dark theme.
    • The preference is retrieved at startup to apply the appropriate theme.

    5. Best Practices for Using SharedPreferences

    While SharedPreferences is simple and effective for storing small amounts of data, you should keep a few best practices in mind:

    • Use a dedicated file for your preferences: Avoid using default SharedPreferences for storing app settings. Use a named file (e.g., "AppSettings") to keep things organized.
    • Store only primitive data types: SharedPreferences is meant for simple data like String, int, boolean, etc. It’s not suitable for storing complex objects like arrays or custom objects (for those, you might want to use a database or file storage).
    • Do not store sensitive data: Avoid storing sensitive information like passwords or user credentials in SharedPreferences unless encrypted. It’s not secure for sensitive data.
    • Clear old preferences: If an app feature is removed or a setting is no longer necessary, make sure to clean up old preferences.

    6. Conclusion

    SharedPreferences is a powerful tool in Android for storing small, simple pieces of data that need to persist across app launches. It is perfect for saving user settings, configurations, and states like login information or theme preferences. By understanding how to save, retrieve, and delete preferences, you can provide a personalized experience for users while keeping your app lightweight and responsive.

    Previous topic 16
    Views
    Next topic 18
    Persisting & Sharing Data

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time5 min
      Word count923
      Code examples0
      DifficultyIntermediate