ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-333User Preferences
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-333

    Mobile Application Development

    Progress0 / 33 done
    Topics33
    1Mobiles Application Development Platform2HTML5 for Mobiles
    3Architecture, Framework and Application Development
    4Architecture, Framework5Application Development with Windows Mobile6Eclipse7Fragments8Calling Built-in Applications using Intents9Displaying Notifications10Components of a Screen11Adapting to Display Orientation12Managing Changes to Screen Orientation13Utilizing the Action Bar14Creating the User Interface15Listening for UI Notifications16Views17User Preferences18Persisting & Sharing Data19Sending SMS Messages20Getting Feedback21Sending E-mail22Displaying Maps23Consuming Web Services Using HTTP
    24Accessing and Creating25Threading26Publishing Android Applications27Deployment on App Stores28Mobile Programming Languages29Challenges with Mobility and Wireless Communication30Location-aware Applications31Performance/Power Tradeoffs32Mobile Platform Constraints33Emerging Technologies
    5 min read
    Topic 17 of 33
    Topic Study Note Illustration
    17

    User Preferences

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    923words
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development