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
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
:
SharedPreferences
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)
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 }
SharedPreferences
Obtain an instance of SharedPreferences
(as shown above).
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.
SharedPreferences
Obtain an instance of SharedPreferences
(as shown above).
Remove specific data:
with(sharedPref.edit()) { remove("username") apply() }
Clear all data:
with(sharedPref.edit()) { clear() apply() }
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.
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.
Data Types: SharedPreferences
supports storing boolean
, float
, int
, long
, and string
data types.
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.
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.
Working with Shared Preferences in Android example code:
// 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");
Storing and retrieving data using Shared Preferences:
// 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);
Customizing Shared Preferences in Android:
// 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();
Shared Preferences vs SQLite in Android:
// Using SQLite for more complex data storage
Handling complex data in Shared Preferences Android:
// Storing and retrieving a JSON object in Shared Preferences
Using Shared Preferences for user settings in Android:
// Storing and retrieving user settings
Securely storing data in Shared Preferences Android:
// Using encryption or other security measures for data in Shared Preferences
Shared Preferences and data persistence in Android:
// Ensuring data persistence using Shared Preferences
Managing SharedPreferences keys and values in Android:
// 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();
SharedPreferences in Android with Kotlin examples:
// 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")
SharedPreferences and SharedPreferences.Editor in Android:
// 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();
Clearing SharedPreferences in Android:
// Clearing all data in Shared Preferences SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.apply();
SharedPreferences and app upgrades in Android:
// Handling Shared Preferences during app upgrades